예제 #1
0
        private string ParamAlias(int i, DocHandler doc)
        {
            var name = Proto.Name;

            if (!doc.Prototypes.ContainsKey(name))
            {
                if (Alias != null && !string.IsNullOrEmpty(Alias.Name))
                {
                    if (doc.Prototypes.ContainsKey(Alias.Name))
                    {
                        name = Alias.Name;
                    }
                }
            }
            if (!doc.Prototypes.ContainsKey(name))
            {
                return(Param[i].OrigName);
            }

            if (doc.Prototypes[name].Params.Count <= i)
            {
                return(Param[i].OrigName);
            }
            return(doc.Prototypes[name].Params[i]);
        }
예제 #2
0
        public void Ctor()
        {
            // arrange
            Mock.SetupStatic(typeof(Ioc));

            // act
            var handler = new DocHandler();

            // assert
            var privateAccessor = new PrivateAccessor(handler);
            Assert.IsNull(privateAccessor.GetField("_fileProcessorUri"));
            Assert.IsNull(privateAccessor.GetField("_tempDocumentUnc"));

            // arrange
            Mock.Arrange(() => SystemOptionsInfo.GetSystemOptionsInfo()).Returns(new SystemOptionsInfo
                {
                    FileProcessorURI = "http://*****:*****@"D:\Projects\Cebos\release-2.2\Cebos.Veyron.Web\FileStorage"
                });

            // act
            handler = new DocHandler();

            // assert
            privateAccessor = new PrivateAccessor(handler);
            Assert.AreEqual("http://*****:*****@"D:\Projects\Cebos\release-2.2\Cebos.Veyron.Web\FileStorage", privateAccessor.GetField("_tempDocumentUnc"));
        }
예제 #3
0
파일: Editor.cs 프로젝트: of22/Essential
        public AbstractHandler IdentifyDoc(string fileName)
        {
            string          format          = fileName.Split('.').Last();
            AbstractHandler abstractHandler = null;

            switch (format)
            {
            case "txt":
                abstractHandler = new TxtHandler();
                break;

            case "doc":
                abstractHandler = new DocHandler();
                break;

            case "xml":
                abstractHandler = new XmlHandler();
                break;

            default:
                Console.WriteLine("Unidentified format");
                break;
            }
            return(abstractHandler);
        }
 /// <summary>
 /// Returns a string with the Supplier/Purchase Invoice numbers if the invoice numbers have been retrieved, or empty string otherwise
 /// </summary>
 /// <param name="docHandler">DocHandler object that allows us access to<see cref="GetPurchaseDocumentsAs_SupplierPurchaseInvoicesGrouping"/> method,
 /// used to format the string</param>
 public string InitialiseExporterStatementPart2(IDocHandler docHandler)
 {
     if (MainViewModel.SalesInvoiceContent != null)
     {
         docHandler = new DocHandler();
         return(docHandler.GetPurchaseDocumentsAs_SupplierPurchaseInvoicesGrouping(MainViewModel.SalesInvoiceContent));
     }
     return("");
 }
예제 #5
0
 public string Filename(DocHandler doc, Registry reg)
 {
     if (!doc.map.ContainsKey(Proto.Name))
     {
         if (Alias != null && !string.IsNullOrEmpty(Alias.Name))
         {
             if (doc.map.ContainsKey(Alias.Name))
             {
                 return(doc.map[Alias.Name]);
             }
             else
             {
                 return(reg.Commands.Command.First(x => x.Proto.Name == Alias.Name).Filename(doc, reg));
             }
         }
         return(string.Empty);
     }
     else
     {
         return(doc.map[Proto.Name]);
     }
 }
예제 #6
0
        public void ProcessRequest_Main()
        {
            // arrange
            Mock.SetupStatic(typeof(Ioc));
            var handler = new DocHandler();

            var context = Mock.Create<HttpContext>();

            Mock.Arrange(() => context.Request.QueryString).Returns(new NameValueCollection
                {
                    { Constants.FileProcessFileName, "77F3EB4C-5FF8-4D50-AC7C-A8E417A6AA3A.txt" },
                    { "BypassAuth", "true" } // necessary to run tests on the server
                });

            var privateAccessor = new PrivateAccessor(handler);
            privateAccessor.SetField("_fileProcessorUri", "http://localhost:5556/DocumentProcessor.ashx");

            var webRequest = WebRequest.Create("http://localhost:5556/DocumentProcessor.ashx?FileName=77F3EB4C-5FF8-4D50-AC7C-A8E417A6AA3A.txt");

            Mock.Arrange(() => WebRequest.Create(Arg.IsAny<Uri>())).Returns(webRequest);

            var response = Mock.Create<WebResponse>(Behavior.Loose);
            Mock.Arrange(() => response.ContentLength).Returns(1);

            Mock.Arrange(() => webRequest.GetResponse()).Returns(response);

            var responseWriteMethodWasCalled = false;
            Mock.Arrange(() => context.Response.Write("File not found. FileName = 77F3EB4C-5FF8-4D50-AC7C-A8E417A6AA3A.txt")).DoInstead(() => responseWriteMethodWasCalled = true);

            // act
            handler.ProcessRequest(context);

            // assert
            Assert.IsTrue(responseWriteMethodWasCalled);
            Assert.AreEqual("text/plain", context.Response.ContentType);

            // arrange
            var stream = Mock.Create<Stream>(Behavior.CallOriginal);

            var exit = false;
            Mock.Arrange(() => stream.Read(Arg.IsAny<byte[]>(), 0, Arg.AnyInt)).Returns(() =>
            {
                if (!exit)
                {
                    exit = true;
                    return Constants.FileProcessBufferSize;
                }

                return 0;
            });

            Mock.Arrange(() => response.GetResponseStream()).Returns(stream);

            var outputStreamWriteMethodWasCalled = false;
            Mock.Arrange(() => context.Response.OutputStream.Write(Arg.IsAny<byte[]>(), 0, Arg.AnyInt)).DoInstead(() => outputStreamWriteMethodWasCalled = true);

            // act
            handler.ProcessRequest(context);

            // assert
            Assert.IsTrue(outputStreamWriteMethodWasCalled);
        }
예제 #7
0
        public void ProcessRequest_ConvertedPDFDoesNotExist_RequestRedirected()
        {
            // arrange
            Mock.SetupStatic(typeof(Ioc));
            var handler = new DocHandler();

            var context = Mock.Create<HttpContext>();

            Mock.Arrange(() => context.Request.QueryString).Returns(new NameValueCollection
                {
                    { "FileId", "1" },
                    { "BypassAuth", "true" } // necessary to run tests on the server
                });

            var dynamicTypeManager = Mock.Create<IDynamicTypeManager>(Behavior.CallOriginal);

            var fileProcess = Mock.Create<IFileProcess>(Behavior.Loose);
            fileProcess.FileName = "77F3EB4C-5FF8-4D50-AC7C-A8E417A6AA3A.txt.pdf";

            Mock.Arrange(() => dynamicTypeManager.GetEditableRoot<IFileProcess>(Constants.FileProcessName, 1)).
                Returns<string, int>((processName, id) => fileProcess);

            handler.TheDynamicTypeManager = dynamicTypeManager;

            var privateAccessor = new PrivateAccessor(handler);
            privateAccessor.SetField("_fileProcessorUri", "http://localhost:5556/DocumentProcessor.ashx");

            var webRequest = WebRequest.Create("http://localhost:5556/DocumentProcessor.ashx?FileName=77F3EB4C-5FF8-4D50-AC7C-A8E417A6AA3A.txt.pdf");

            Mock.Arrange(() => WebRequest.Create(Arg.IsAny<Uri>())).Returns(webRequest);

            var response = Mock.Create<WebResponse>(Behavior.Loose);

            Mock.Arrange(() => response.ContentLength).Returns(0);
            Mock.Arrange(() => webRequest.GetResponse()).Returns(response);

            var called = false;
            Mock.Arrange(() => context.Response.Redirect("http://localhost:5556/DocumentProcessor.ashx?FileName=77F3EB4C-5FF8-4D50-AC7C-A8E417A6AA3A.txt")).DoInstead(() => called = true);

            // act
            handler.ProcessRequest(context);

            // we don't redirect anymore
            //Assert.IsTrue(called);

            Assert.IsFalse(called);
        }
예제 #8
0
        public void ProcessRequest_ResponseIsEmptyStream()
        {
            // arrange
            Mock.SetupStatic(typeof(Ioc));
            var handler = new DocHandler();

            var context = Mock.Create<HttpContext>();

            Mock.Arrange(() => context.Request.QueryString).Returns(new NameValueCollection
                {
                    { "FileId", "1" },
                    { "BypassAuth", "true" } // necessary to run tests on the server
                });

            var dynamicTypeManager = Mock.Create<IDynamicTypeManager>(Behavior.CallOriginal);

            var fileProcess = Mock.Create<IFileProcess>(Behavior.Loose);
            fileProcess.FileName = "77F3EB4C-5FF8-4D50-AC7C-A8E417A6AA3A.txt";

            Mock.Arrange(() => dynamicTypeManager.GetEditableRoot<IFileProcess>(Constants.FileProcessName, 1)).
                Returns<string, int>((processName, id) => fileProcess);

            handler.TheDynamicTypeManager = dynamicTypeManager;

            var privateAccessor = new PrivateAccessor(handler);
            privateAccessor.SetField("_fileProcessorUri", "http://localhost:5556/DocumentProcessor.ashx");

            var webRequest = WebRequest.Create("http://localhost:5556/DocumentProcessor.ashx?FileName=77F3EB4C-5FF8-4D50-AC7C-A8E417A6AA3A.txt");

            Mock.Arrange(() => WebRequest.Create(Arg.IsAny<Uri>())).Returns(webRequest);

            var response = Mock.Create<WebResponse>(Behavior.Loose);
            
            Mock.Arrange(() => webRequest.GetResponse()).Returns(response);

            var called = false;
            Mock.Arrange(() => context.Response.Write("The file was deleted manually, or maybe, path is incorrect\r\nFull address is: http://localhost:5556/DocumentProcessor.ashx?FileName=77F3EB4C-5FF8-4D50-AC7C-A8E417A6AA3A.txt")).DoInstead(() => called = true);

            // act
            handler.ProcessRequest(context);

            // assert
            Assert.AreEqual("text/plain", context.Response.ContentType);
            Assert.IsTrue(called);
        }
예제 #9
0
        public void ProcessRequest_RedirectAndAuthentication()
        {
            // arrange
            Mock.SetupStatic(typeof(Ioc));
            var handler = new DocHandler();

            var context = Mock.Create<HttpContext>();

            // returns HttpValueCollection
            var queryString = HttpUtility.ParseQueryString(string.Empty);
            queryString["FileId"] = "1";
            queryString["BypassAuth"] = "false";

            Mock.Arrange(() => context.Request.QueryString).Returns(queryString);

            Mock.Arrange(() => Csla.ApplicationContext.User.Identity.IsAuthenticated).Returns(false);
            Mock.Arrange(() => ConfigurationManager.AppSettings["ApplicationRootUrl"]).Returns("http://localhost:5558/");

            var called = false;
            Mock.Arrange(() => context.Response.Redirect("http://localhost:5558/?FileId=1&BypassAuth=false")).DoInstead(() => called = true);

            // act
            handler.ProcessRequest(context);

            // assert
            Assert.IsTrue(called);

            // arrange
            called = false;

            Mock.Arrange(() => ConfigurationManager.AppSettings["ApplicationRootUrl"]).Returns((string)null);

            // act
            handler.ProcessRequest(context);

            // assert
            Assert.IsFalse(called);

            // arrange
            called = false;

            Mock.Arrange(() => ConfigurationManager.AppSettings["ApplicationRootUrl"]).Returns("http://localhost:5558/");

            // act
            handler.ProcessRequest(context);

            // assert
            Assert.IsTrue(called);

            // arrage
            called = false;
            Mock.Arrange(() => context.Response.Redirect(Arg.AnyString)).DoInstead(() => called = true);

            Mock.Arrange(() => ConfigurationManager.AppSettings["ApplicationRootUrl"]).Returns("not valid url");

            // act
            handler.ProcessRequest(context);

            // assert
            Assert.IsFalse(called);

            // arrage
            Mock.Arrange(() => ConfigurationManager.AppSettings["ApplicationRootUrl"]).Returns("http://localhost:5558/");

            Mock.Arrange(() => context.Request.QueryString).Returns(new NameValueCollection
                {
                    { "BypassAuth", "false" }
                });

            // act
            handler.ProcessRequest(context);

            // assert
            Assert.IsFalse(called);
        }
예제 #10
0
        public void ReadFile()
        {
            // arrange
            Mock.SetupStatic(typeof(Ioc));
            var handler = new DocHandler();

            var context = Mock.Create<HttpContext>();

            const string path = @"D:\Reports\1.trdx";

            Mock.Arrange(() => File.Exists(path)).Returns(false);
            Mock.Arrange(() => File.OpenRead(path)).Throws<Exception>();

            var privateAccessor = new PrivateAccessor(handler);
            
            try
            {
                // act
                privateAccessor.CallMethod("ReadFile", new object[] { context, path });
            }
            catch (Exception ex)
            {
                // assert
                Assert.Fail("Expected no exception, but got: " + ex.Message);
            }
            
            // assert
            Assert.AreEqual("text/plain", context.Response.ContentType);

            // arrange
            Mock.Arrange(() => File.Exists(path)).Returns(true);

            var stream = Mock.Create<FileStream>(Behavior.CallOriginal);

            var exit = false;
            Mock.Arrange(() => stream.Read(Arg.IsAny<byte[]>(), 0, Arg.AnyInt)).Returns(() =>
            {
                if (!exit)
                {
                    exit = true;
                    return 1024 * 8;
                }

                return 0;
            });

            Mock.Arrange(() => File.OpenRead(path)).Returns(stream);

            var outputStreamWriteMethodWasCalled = false;
            Mock.Arrange(() => context.Response.OutputStream.Write(Arg.IsAny<byte[]>(), 0, Arg.AnyInt)).DoInstead(() => outputStreamWriteMethodWasCalled = true);

            // act
            privateAccessor.CallMethod("ReadFile", new object[] { context, path });

            // arrange
            Assert.IsTrue(outputStreamWriteMethodWasCalled);
        }
예제 #11
0
        //private static async Task RunDelBatchAsync()
        //{
        //    try
        //    {
        //        DocHandler handler = new DocHandler();
        //        string[] batch = 
        //            { "6f654eb7-569c-4de9-95c6-0bda12417f4b",
        //            "84424d92-a98e-4a36-9cfc-cfa8a9a8d43b",
        //            "2e6dbab8-cbce-4643-8fdc-9d7ca9ba2bbe",
        //            "605e8af8-67f6-41e9-a04a-50d871e18cb7",
        //            "e4346009-05a4-4852-85fc-371cab3ca39e",
        //            "674995f0-a42e-4d24-8f66-2304e4a20385"
        //        };
        //        Task<List<WHResponse>> taskTest = handler.DeleteBatchAsync(batch.ToList());
        //        Task.WaitAll(taskTest);
        //        List<WHResponse> retInt = taskTest.Result;
        //    }
        //    catch (Exception)
        //    {

        //        throw;
        //    }
        //}
        //private static async Task RunDelDocAsync()
        //{
        //    try
        //    {
        //        DocHandler handler = new DocHandler();
        //        Task<WHResponse> taskTest = handler.DeleteDocAsync("f80aa2b3-40fc-4725-b9cf-68f46ad819ab");
        //        Task.WaitAll(taskTest);
        //        WHResponse retObj = taskTest.Result;
        //    }
        //    catch (Exception)
        //    {

        //        throw;
        //    }
        //}

        private static void TestConstructors()
        {
            //open with ID, should succeed
            DocHandler handler = new DocHandler(new Uri(END_PT), AUTH_KEY, COLL_ID);
            handler.Dispose();
            handler = null;

            //open with name, should succeed
            handler = new DocHandler(new Uri(END_PT), AUTH_KEY, DB_NAME, COLL_NAME);
            handler.Dispose();
            handler = null;

            try
            {
                //open with bad end point, should fail
                handler = new DocHandler(new Uri("http://www.google.com"), AUTH_KEY, DB_NAME, COLL_NAME);
            }
            catch (Exception)
            {
                handler = null;
            }
            try
            {
                //open with blank authkey, should fail
                handler = new DocHandler(new Uri(END_PT), "", DB_NAME, COLL_NAME);
            }
            catch (Exception)
            {
                handler = null;
            }
            try
            {
                //open with bad authkey, should fail
                handler = new DocHandler(new Uri(END_PT), string.Concat(AUTH_KEY,"x"), DB_NAME, COLL_NAME);
            }
            catch (Exception)
            {
                handler = null;
            }
            try
            {
                //open with bad dbname, should fail
                handler = new DocHandler(new Uri(END_PT), AUTH_KEY, string.Concat(DB_NAME,"x"), COLL_NAME);
            }
            catch (Exception)
            {
                handler = null;
            }
            try
            {
                //open with blank dbname, should fail
                handler = new DocHandler(new Uri(END_PT), AUTH_KEY, "", COLL_NAME);
            }
            catch (Exception)
            {
                handler = null;
            }
            try
            {
                //open with bad collection name, should fail
                handler = new DocHandler(new Uri(END_PT), AUTH_KEY, DB_NAME, string.Concat(COLL_NAME, "x"));
            }
            catch (Exception)
            {
                handler = null;
            }
            try
            {
                //open with blank collection name, should fail
                handler = new DocHandler(new Uri(END_PT), AUTH_KEY, DB_NAME, "");
            }
            catch (Exception)
            {
                handler = null;
            }
            try
            {
                //open with bad collection id, should fail
                handler = new DocHandler(new Uri(END_PT), AUTH_KEY, string.Concat(COLL_ID,"x"));
            }
            catch (Exception)
            {
                handler = null;
            }
            try
            {
                //open with blank collection id, should fail
                handler = new DocHandler(new Uri(END_PT), AUTH_KEY, "");
            }
            catch (Exception)
            {
                handler = null;
            }
        }
예제 #12
0
        private static async Task RunAddDocAsync()
        {

            try
            {
                //POCO test
                dynamic docDB = new
                {
                    teststring1 = "AddDocAsync POCO testing",
                    teststring2 = DateTime.Now.ToUniversalTime()
                };
                DocHandler handler = new DocHandler(new Uri(END_PT), AUTH_KEY, COLL_ID);
                Task <WHResponse> taskTest = handler.AddDocAsync(docDB);
                Task.WaitAll(taskTest);
                WHResponse respObj = taskTest.Result;

                //string test
                string strJson = string.Concat("{ 'AddDocAsync string testing' : '", DateTime.Now, "'}");
                taskTest = handler.AddDocAsync(strJson);
                Task.WaitAll(taskTest);
                respObj = taskTest.Result;

                //string test - fails - empty string
                strJson = "{ }";
                taskTest = handler.AddDocAsync(strJson);
                Task.WaitAll(taskTest);
                respObj = taskTest.Result;

                //document test
                strJson = string.Concat("{ 'AddDocAsync document testing' : '", DateTime.Now, "'}");
                Document doc = new Document();
                doc.LoadFrom(new JsonTextReader(new StringReader(strJson)));
                taskTest = handler.AddDocAsync(doc);
                Task.WaitAll(taskTest);
                respObj = taskTest.Result;

                //jobject test
                strJson = string.Concat("{ 'AddDocAsync jobject testing' : '", DateTime.Now, "'}");
                JObject jObj = JObject.Parse(strJson);
                taskTest = handler.AddDocAsync(jObj);
                Task.WaitAll(taskTest);
                respObj = taskTest.Result;

                //xml document test
                XmlDocument docXML = new XmlDocument();
                docXML.InnerXml = string.Concat("<testroot><firstField>XML doc test</firstField><secondField>", DateTime.Now, "</secondField></testroot>");
                taskTest = handler.AddDocAsync(docXML);
                Task.WaitAll(taskTest);
                respObj = taskTest.Result;

                //xml string test
                string strXml = string.Concat("<testroot><firstField>XML string test</firstField><secondField>", DateTime.Now, "</secondField></testroot>");
                taskTest = handler.AddDocAsync(strXml);
                Task.WaitAll(taskTest);
                respObj = taskTest.Result;

                //xml string test - fails - bad xml
                strXml = string.Concat("<testroot><firstField>XML string test<firstField><secondField>", DateTime.Now, "</secondField></testroot>");
                taskTest = handler.AddDocAsync(strXml);
                Task.WaitAll(taskTest);
                respObj = taskTest.Result;

                //POCO test - fails - duplicate ID
                docDB = new
                {
                    id = "94a23e36-8xyz-45ce-9189-8624e7e174b9",
                    teststring1 = "AddDocAsync POCO testing - fails",
                    teststring2 = DateTime.Now.ToUniversalTime()
                };
                taskTest = handler.AddDocAsync(docDB);
                Task.WaitAll(taskTest);
                respObj = taskTest.Result;

            }
            catch (Exception)
            {
                throw;
            }
        }
예제 #13
0
        public void Build(IndentedStringBuilder delegates, IndentedStringBuilder pointers, IndentedStringBuilder wrappers, Registry reg, HashSet <string> commands, DocHandler doc)
        {
            var wrapperStart = true;

            foreach (var c in Command)
            {
                c.Proto.ReturnType = Senzible.GetReturnType(c.Proto);
                c.FixParams(reg);
                c.BuildDelegate(delegates);
                c.BuildPointer(pointers);
                if (!wrapperStart)
                {
                    wrappers.AppendLine("");
                }
                else
                {
                    wrapperStart = false;
                }
                c.BuildWrappers(wrappers, doc, reg);
                commands.Add(c.Proto.Name);
            }
        }
예제 #14
0
        public void BuildWrappers(IndentedStringBuilder sb, DocHandler doc, Registry reg)
        {
            var p1    = GetParamVariations();
            var first = true;

            foreach (var p2 in p1)
            {
                if (first)
                {
                    first = false;
                }
                else
                {
                    sb.AppendLine("");
                }

                var filename = Filename(doc, reg);
                if (filename != string.Empty)
                {
                    doc.map[Proto.Name] = filename;
                    doc.WriteMainDoc(sb, Proto.Name);
                    var i = 0;
                    foreach (var param in p2)
                    {
                        doc.WriteParameter(sb, Proto.Name, param.Name, ParamAlias(i, doc));
                        i++;
                    }
                }

                sb.AppendLine("public static {0} {1}({2}) {{",
                              Proto.MarshalString ? "string" : Proto.ReturnType,
                              Proto.Name,
                              string.Join(", ", p2.Select(x => x.DeclareType + " " + x.Name))
                              );
                sb.Indent();
                var fxd = false;
                foreach (var param in p2)
                {
                    if (param.IsFixed)
                    {
                        fxd = true;
                        sb.AppendLine("fixed({0} {1}_ = &{1}[0])", param.FixedType, param.Name);
                    }
                    else if (param.IsOut)
                    {
                        fxd = true;
                        sb.AppendLine("fixed({0} {1}_ = &{1})", param.FixedType, param.Name);
                    }
                }
                if (fxd)
                {
                    sb.Indent();
                }
                sb.AppendLine("{0}{2}Pointers.{1}({3}){4};",
                              Proto.ReturnType == "void" ? "" : "return ",
                              Proto.Name,
                              Proto.MarshalString ? "PtrToStringUTF8(" : "",
                              string.Join(", ", p2.Select(x => x.Param)),
                              Proto.MarshalString ? ")" : ""
                              );
                if (fxd)
                {
                    sb.Outdent();
                }
                sb.Outdent();
                sb.AppendLine("}");
            }

            if (
                (Proto.Name.StartsWith("glGen") || Proto.Name.StartsWith("glCreate")) &&
                Proto.ReturnType == "void" &&
                Param.Count == 2 &&
                Param.Any(x => x.NeedsFixed && !string.IsNullOrEmpty(x.Len) && Param.Any(y => y.Name == x.Len && y.Name != x.Name))
                )
            {
                var param = Param.First(x => !string.IsNullOrEmpty(x.Len));
                sb.AppendLine("");
                sb.AppendLine("public static {0} {1}() {{",
                              param.Translated.Substring(0, param.Translated.Length - 1),
                              Proto.Name.EndsWith("s") ? Proto.Name.Substring(0, Proto.Name.Length - 1) : Proto.Name
                              );
                sb.Indent();
                sb.AppendLine("var {0}_ = new {1}[1];", param.Name, param.Translated.Substring(0, param.Translated.Length - 1));
                sb.AppendLine("{0}(1, {1}_);", Proto.Name, param.Name);
                sb.AppendLine("return {0}_[0];", param.Name);
                sb.Outdent();
                sb.AppendLine("}");
            }

            if (new[] { "glGetIntegerv", "glGetFloatv", "glGetDoublev", "glGetBooleanv" }.Contains(Proto.Name))
            {
                sb.AppendLine("");
                var param = Param.First(x => x.NeedsFixed);
                sb.AppendLine("public static {0} {1}({2}) {{",
                              param.Translated.Substring(0, param.Translated.Length - 1),
                              Proto.Name,
                              string.Join(", ", Param.Where(x => x != param).Select(x => x.Translated + " " + x.Name))
                              );
                sb.Indent();
                sb.AppendLine("{0} {1};", param.Translated.Substring(0, param.Translated.Length - 1), param.Name);
                sb.AppendLine("{0}({1});",
                              Proto.Name,
                              string.Join(", ", Param.Select(x => (x == param ? "&" : "") + x.Name))
                              );
                sb.AppendLine("return {0};", param.Name);
                sb.Outdent();
                sb.AppendLine("}");
            }
        }
예제 #15
0
        public void ProcessRequest_WhenUserUseIE()
        {
            // arrange
            Mock.SetupStatic(typeof(Ioc));
            var handler = new DocHandler();

            var context = Mock.Create<HttpContext>();

            var fileName = Guid.NewGuid() + ".mp4";

            Mock.Arrange(() => context.Request.QueryString).Returns(new NameValueCollection
                {
                    { Constants.FileProcessFileName, fileName },
                    { "BypassAuth", "true" } // necessary to run tests on the server
                });

            var privateAccessor = new PrivateAccessor(handler);
            privateAccessor.SetField("_fileProcessorUri", "http://localhost:5556/DocumentProcessor.ashx");

            var webRequest = WebRequest.Create("http://localhost:5556/DocumentProcessor.ashx?FileName=" + fileName);

            Mock.Arrange(() => WebRequest.Create(Arg.IsAny<Uri>())).Returns(webRequest);

            var response = Mock.Create<WebResponse>(Behavior.Loose);
            Mock.Arrange(() => response.ContentLength).Returns(1);

            Mock.Arrange(() => webRequest.GetResponse()).Returns(response);

            var stream = Mock.Create<Stream>(Behavior.CallOriginal);

            var exit = false;
            Mock.Arrange(() => stream.Read(Arg.IsAny<byte[]>(), 0, Arg.AnyInt)).Returns(() =>
            {
                if (!exit)
                {
                    exit = true;
                    return Constants.FileProcessBufferSize;
                }

                return 0;
            });

            Mock.Arrange(() => response.GetResponseStream()).Returns(stream);

            Mock.Arrange(() => context.Request.Browser.Browser).Returns("IE");

            privateAccessor.SetField("_tempDocumentUnc", Path.GetTempPath());

            Mock.Arrange(() => ConfigurationManager.AppSettings["ApplicationRootUrl"]).Returns("http://localhost:5558/");

            var redirectExecuted = false;

            var tmp = string.Format("http://localhost:5558/{0}/{1}", new DirectoryInfo(Path.GetTempPath()).Name, fileName);

            Mock.Arrange(() => context.Response.Redirect(tmp)).DoInstead(() => redirectExecuted = true);

            // act
            handler.ProcessRequest(context);

            // assert
            Assert.IsTrue(redirectExecuted);
        }
예제 #16
0
        public void ProcessRequest_CatchException()
        {
            // arrange
            Mock.SetupStatic(typeof(Ioc));
            var handler = new DocHandler();

            var context = Mock.Create<HttpContext>();

            Mock.Arrange(() => context.Request.QueryString).Returns(new NameValueCollection
                {
                    { Constants.FileProcessFileName, "77F3EB4C-5FF8-4D50-AC7C-A8E417A6AA3A.txt" },
                    { "BypassAuth", "true" } // necessary to run tests on the server
                });

            var writeWasCalled = false;
            Mock.Arrange(() => context.Response.Write(Arg.AnyString)).DoInstead(() => writeWasCalled = true);

            var wasLogged = false;
            Mock.Arrange(() => Log4NetLogger.Instance.Log(LogSeverity.Error, typeof(DocHandler).FullName, Arg.IsAny<Exception>())).DoInstead(() => wasLogged = true);

            // act
            handler.ProcessRequest(context);

            // assert
            Assert.IsTrue(writeWasCalled);
            Assert.IsTrue(wasLogged);
        }
예제 #17
0
        public void ProcessRequest_LicenseFile()
        {
            // arrange
            Mock.SetupStatic(typeof(Ioc));
            var handler = new DocHandler();

            var context = Mock.Create<HttpContext>();
            Mock.Arrange(() => context.Request.QueryString).Returns(new NameValueCollection
                {
                    { "FileId", "1" },
                    { "LicenseFileName", "license.txt" },
                    { "BypassAuth", "true" } // necessary to run tests on the server
                });

            var called = false;
            Mock.NonPublic.Arrange(handler, "LoadLicenseFile", new object[] { context, "license.txt" }).DoInstead(() => called = true);

            // act
            handler.ProcessRequest(context);

            // assert
            Assert.IsTrue(called);
        }
예제 #18
0
        public void LoadLicenseFile()
        {
            // arrange
            Mock.SetupStatic(typeof(Ioc));
            var handler = new DocHandler();

            var context = Mock.Create<HttpContext>();

            const string licenseFileName = "LicenseFileName.txt";

            Mock.Arrange(() => context.Server.MapPath("~/ServerBin/" + licenseFileName)).Returns(Path.Combine(Path.GetTempPath(), licenseFileName));

            var exit = false;
            Mock.Arrange(() => context.Request.InputStream.Read(Arg.IsAny<byte[]>(), 0, Arg.AnyInt)).Returns(() =>
            {
                if (!exit)
                {
                    exit = true;
                    return 4096;
                }

                return 0;
            });

            var called = false;
            Mock.Arrange(() => LicenseInfo.ReloadLicense()).DoInstead(() => called = true);

            // act
            var privateAccessor = new PrivateAccessor(handler);
            privateAccessor.CallMethod("LoadLicenseFile", new object[] {context, "LicenseFileName.txt"});

            // assert
            Assert.IsTrue(called);
        }
예제 #19
0
        public void ProcessRequest_FileNameIsEmpty()
        {
            // arrange
            Mock.SetupStatic(typeof(Ioc));
            var handler = new DocHandler();

            var context = Mock.Create<HttpContext>();

            Mock.Arrange(() => context.Request.QueryString).Returns(new NameValueCollection
                {
                    { Constants.FileProcessFileName, null },
                    { "BypassAuth", "true" } // necessary to run tests on the server
                });

            var called = false;
            Mock.Arrange(() => context.Response.Write("File does not exist")).DoInstead(() => called = true);

            // act
            handler.ProcessRequest(context);

            // assert
            Assert.AreEqual("text/plain", context.Response.ContentType);
            Assert.IsTrue(called);

            // arrange
            called = false;
            context.Response.ContentType = null;

            Mock.Arrange(() => context.Request.QueryString).Returns(new NameValueCollection
                {
                    { Constants.FileProcessFileName, string.Empty },
                    { "BypassAuth", "true" } // necessary to run tests on the server
                });

            // act
            handler.ProcessRequest(context);

            // assert
            Assert.AreEqual("text/plain", context.Response.ContentType);
            Assert.IsTrue(called);
        }
예제 #20
0
        public void IsReusable()
        {
            // arrange
            Mock.SetupStatic(typeof(Ioc));
            var handler = new DocHandler();

            // act
            var result = handler.IsReusable;

            // assert
            Assert.IsTrue(result);
        }
예제 #21
0
        public void ProcessRequest_ReportFileName()
        {
            // arrange
            Mock.SetupStatic(typeof(Ioc));
            var handler = new DocHandler();

            var context = Mock.Create<HttpContext>();

            var privateAccessor = new PrivateAccessor(handler);
            privateAccessor.SetField("_reportsPath", "D:\\Reports" );

            Mock.Arrange(() => context.Request.QueryString).Returns(new NameValueCollection
                {
                    { "ReportFileName", "1.trdx" },
                    { "BypassAuth", "true" } // necessary to run tests on the server
                });

            var called = false;
            Mock.NonPublic.Arrange(handler, "ReadFile", new object[] { context, @"D:\Reports\1.trdx" }).DoInstead(() => called = true);

            // act
            handler.ProcessRequest(context);

            // assert
            Assert.IsTrue(called);
        }