private void FindFloorFaces() { Options options = new Options(); options.ComputeReferences = true; foreach (Element element in settings.SelectedElements) { Floor floor = element as Floor; if (null != floor) { GeometryElement geomElem = floor.get_Geometry(options); if (null != geomElem) { foreach (GeometryObject geomObj in geomElem) { Solid solid = geomObj as Solid; if (solid != null) { foreach (Face face in solid.Faces) { if (AnalysisHelper.DetermineFaceDirection(face, DisplayingFaces.Top)) { if (!floorFaces.ContainsKey(floor.Id.IntegerValue)) { floorFaces.Add(floor.Id.IntegerValue, face); } } } } } } } } }
public AnalysisResult Analyze(Network network, Dictionary <string, string> parameters) { var errors = ValidateParameters(network, parameters); if (errors.Count > 0) { // TODO: custom exception throw new ArgumentException(string.Join('\n', errors)); } var treshold = int.Parse(parameters["treshold"]); var algorithm = ParseAlgorithm(parameters); var communities = Algorithm.Apply(network, algorithm, treshold); return(new AnalysisResult { ActorToCommunity = AnalysisHelper.ActorToCommunity(network.Actors, communities), AnalyzedNetworkEdgeList = AnalysisHelper.EdgeList(network), CommunityList = AnalysisHelper.CommunityList(network.Actors, communities), Exclusivities = AnalysisHelper.Exclusivities(network, communities), Homogenities = AnalysisHelper.Homogenities(network, communities), Varieties = AnalysisHelper.Varieties(network, communities), Performances = AnalysisHelper.Performances(network, communities), Coverages = AnalysisHelper.Coverages(network, communities), Modularities = AnalysisHelper.Modularities(network, communities) }); }
public void OnNavigateNoDocumentTest() { var mockDte = new Mock <DTE>(MockBehavior.Strict); this.mockServiceProvider.Setup(sp => sp.GetService(typeof(EnvDTE.DTE))).Returns(mockDte.Object); this.mockServiceProvider.Setup(sp => sp.GetService(typeof(SVsSolutionBuildManager))).Returns(new MockSolutionBuildManager()); AnalysisHelper analysisHelper = this.SetCoreNoUI(); bool eventFired = false; var styleCopCore = (StyleCopCore)typeof(AnalysisHelper) .GetField("core", BindingFlags.Instance | BindingFlags.NonPublic) .GetValue(analysisHelper); styleCopCore.OutputGenerated += (sender, args) => { eventFired = true; }; // ProjectUtilities.Initialize(this.mockServiceProvider.Instance); // Does nothing - included for code coverage and to catch it if it starts doing something unexpectedtly this.taskUnderTestShell.Document = null; typeof(ViolationTask).GetMethod("OnNavigate", BindingFlags.Instance | BindingFlags.NonPublic) .Invoke(this.taskUnderTest, new object[] { EventArgs.Empty }); Assert.IsTrue(eventFired, "Core did not fire output event"); // Reset Factory.ServiceProvider. typeof(ProjectUtilities).GetField("serviceProvider", BindingFlags.Static | BindingFlags.NonPublic) .SetValue(null, null); }
public Result DeleteRepairRecord([FromBody] BatchDelete batchDelete) { var ids = batchDelete.ids; var data = ServerConfig.ApiDb.Query <RepairRecord>("SELECT * FROM `fault_device_repair` WHERE Id IN @id AND `State` = @state AND MarkedDelete = 0;", new { id = ids, state = RepairStateEnum.Complete }); if (data.Count() != ids.Count()) { return(Result.GenError <Result>(Error.RepairRecordNotExist)); } ServerConfig.ApiDb.Execute( "UPDATE `fault_device_repair` SET `MarkedDateTime`= @MarkedDateTime, `MarkedDelete`= @MarkedDelete, `Cancel`= @Cancel WHERE `Id`IN @Id;", new { MarkedDateTime = DateTime.Now, MarkedDelete = true, Cancel = true, Id = ids }); foreach (var d in data.GroupBy(x => x.FaultTime).Select(x => x.Key)) { AnalysisHelper.FaultCal(d); } foreach (var d in data.GroupBy(x => x.SolveTime).Select(x => x.Key)) { AnalysisHelper.FaultCal(d); } return(Result.GenError <Result>(Error.Success)); }
private void FindRoomFaces() { Options options = new Options(); options.ComputeReferences = true; options.IncludeNonVisibleObjects = true; foreach (Element element in settings.SelectedElements) { Room room = element as Room; GeometryElement geomElem = null; if (null != room) { geomElem = room.get_Geometry(options); } if (null != geomElem) { foreach (GeometryObject geomObj in geomElem) { Solid solid = geomObj as Solid; if (solid != null) { foreach (Face face in solid.Faces) { if (AnalysisHelper.DetermineFaceDirection(face, DisplayingFaces.Bottom)) { //roomFaces.Add(room.Id.IntegerValue, CreateGeometry(face)); roomFaces.Add(room.Id.IntegerValue, face); } } } } } } }
public void OnNavigateNoDocumentTest() { try { bool eventFired = false; Mock <DTE> mockDte = new Mock <DTE>(); // No UI for test AnalysisHelper analysisHelper = this.SetCoreNoUI(); PrivateObject actual = new PrivateObject(this.package, new PrivateType(typeof(StyleCopVSPackage))); actual.SetFieldOrProperty("core", this.package.Core); // Register output generated event to test event fired this.package.Core.OutputGenerated += (sender, args) => { eventFired = true; }; // Does nothing - included for code coverage and to catch it if it starts doing something unexpectedly Assert.IsNotNull(this.taskUnderTestShell, "this.taskUnderTestShell is null."); this.taskUnderTestShell.Document = null; // Use private type to set static private field PrivateType privateProjectUtilities = new PrivateType(typeof(ProjectUtilities)); privateProjectUtilities.SetStaticFieldOrProperty("serviceProvider", this.mockServiceProvider.Instance); PrivateObject taskUnderTestPrivateObject = new PrivateObject(this.taskUnderTest, new PrivateType(typeof(ViolationTask))); taskUnderTestPrivateObject.Invoke("OnNavigate", EventArgs.Empty); Assert.IsTrue(eventFired, "Core did not fire output event"); } catch (Exception ex) { // Use try catch to test a workaround on CI build (AppVeyor) Console.WriteLine(ex.Message); } }
public void OnNavigateToDocNotInProjectTest() { try { var mockDocumentEnumerator = new SequenceMock <IEnumerator>(); var mockDte = new Mock <DTE>(); var mockDocuments = new Mock <Documents>(); var mockDocument = new SequenceMock <Document>(); var mockActiveDocument = new Mock <Document>(); var mockTextSelection = new SequenceMock <TextSelection>(); var mockVirtualPoint = new SequenceMock <VirtualPoint>(); this.SetupProjectUtilities(mockDocumentEnumerator, mockDte, mockDocuments, mockDocument, mockActiveDocument, "DummyFile.txt"); var mockSecondDocument = new SequenceMock <Document>(); mockDocumentEnumerator.AddExpectationExpr(docs => docs.MoveNext(), true); mockDocumentEnumerator.AddExpectationExpr(docs => docs.Current, mockSecondDocument.Instance); mockDocumentEnumerator.AddExpectationExpr(docs => docs.MoveNext(), false); mockSecondDocument.AddExpectationExpr(doc => doc.FullName, "DummyFile.txt"); AnalysisHelper analysisHelper = this.SetCoreNoUI(); bool eventFired = false; PrivateObject actual = new PrivateObject(this.package, new PrivateType(typeof(StyleCopVSPackage))); actual.SetFieldOrProperty("core", this.package.Core); // Register output generated event to test event fired this.package.Core.OutputGenerated += (sender, args) => { eventFired = true; }; mockActiveDocument.ImplementExpr(doc => doc.Selection, mockTextSelection.Instance); mockTextSelection.ImplementExpr(sel => sel.GotoLine(this.violation.LineNumber, true)); mockTextSelection.ImplementExpr(sel => sel.ActivePoint, mockVirtualPoint.Instance); mockVirtualPoint.ImplementExpr(vp => vp.TryToShow(EnvDTE.vsPaneShowHow.vsPaneShowCentered, 0)); this.mockServiceProvider.ImplementExpr(sp => sp.GetService(typeof(EnvDTE.DTE)), mockDte.Instance); // Use private type to set static private field PrivateType privateProjectUtilities = new PrivateType(typeof(ProjectUtilities)); privateProjectUtilities.SetStaticFieldOrProperty("serviceProvider", this.mockServiceProvider.Instance); // Execute PrivateObject taskUnderTestPrivateObject = new PrivateObject(this.taskUnderTest, new PrivateType(typeof(ViolationTask))); taskUnderTestPrivateObject.Invoke("OnNavigate", EventArgs.Empty); // Verify the required methods are called to show the violation mockTextSelection.Verify(); mockVirtualPoint.Verify(); mockDocument.Verify(); Assert.IsTrue(eventFired, "Core did not fire output event"); } catch (Exception ex) { // Use try catch to test a workaround on CI build (AppVeyor) Console.WriteLine(ex.Message); } }
private string AnalysisTransferInfo(string connectid, string content) { ProtocolTransferMessageRequest request = AnalysisHelper.ToProtocol <ProtocolTransferMessageRequest>(content); ProtocolTransferMessageResponse response = new ProtocolTransferMessageResponse(); SendMessage(connectid, AnalysisHelper.ToJson(response)); return(string.Empty); }
public void AnalysisHelperConstructorTest() { IServiceProvider serviceProvider = new MockServiceProvider(); StyleCopCore core = new StyleCopCore(); FileAnalysisHelper specificTarget = new FileAnalysisHelper(serviceProvider, core); AnalysisHelper target = specificTarget; Assert.IsNotNull(target, "Unable to instantiate the AnalysisHelper class"); Assert.IsNotNull(target.Core, "AnalysisHelper.Core was null"); }
public void OnNavigateToDocNotInProjectTest() { var mockDocumentEnumerator = new Mock <IEnumerator>(MockBehavior.Strict); var mockDte = new Mock <DTE>(MockBehavior.Strict); var mockDocuments = new Mock <Documents>(MockBehavior.Strict); var mockDocument = new Mock <Document>(MockBehavior.Strict); var mockActiveDocument = new Mock <Document>(MockBehavior.Strict); var mockTextSelection = new Mock <TextSelection>(MockBehavior.Strict); this.SetupProjectUtilities(mockDocumentEnumerator, mockDte, mockDocuments, mockDocument, mockActiveDocument); var mockSecondDocument = new Mock <Document>(MockBehavior.Strict); var mockDocumentEnumeratorSequence = new MockSequence(); mockDocumentEnumerator.InSequence(mockDocumentEnumeratorSequence).Setup(docs => docs.MoveNext()) .Returns(true); mockDocumentEnumerator.InSequence(mockDocumentEnumeratorSequence).SetupGet(docs => docs.Current) .Returns(mockSecondDocument.Object); mockDocumentEnumerator.InSequence(mockDocumentEnumeratorSequence).Setup(docs => docs.MoveNext()) .Returns(false); mockSecondDocument.SetupGet(doc => doc.FullName).Returns("DummyFile.txt"); AnalysisHelper analysisHelper = this.SetCoreNoUI(); bool eventFired = false; var styleCopCore = (StyleCopCore)typeof(AnalysisHelper) .GetField("core", BindingFlags.Instance | BindingFlags.NonPublic) .GetValue(analysisHelper); styleCopCore.OutputGenerated += (sender, args) => { eventFired = true; }; mockActiveDocument.SetupGet(doc => doc.Selection).Returns(mockTextSelection.Object); var mockTextSelectionSequence = new MockSequence(); mockTextSelection.InSequence(mockTextSelectionSequence).Setup(sel => sel.GotoLine(this.violation.LineNumber, true)); this.mockServiceProvider.Setup(sp => sp.GetService(typeof(EnvDTE.DTE))).Returns(mockDte.Object); typeof(ProjectUtilities).GetField("serviceProvider", BindingFlags.Static | BindingFlags.NonPublic) .SetValue(null, this.mockServiceProvider.Object); // Execute typeof(ViolationTask).GetMethod("OnNavigate", BindingFlags.Instance | BindingFlags.NonPublic) .Invoke(this.taskUnderTest, new object[] { EventArgs.Empty }); // Verify the required methods are called to show the violation mockTextSelection.VerifyAll(); mockDocument.VerifyAll(); Assert.IsTrue(eventFired, "Core did not fire output event"); }
public AnalysisResult Analyze(Network network, Dictionary <string, string> parameters) { var communities = Algorithm.Apply(network); return(new AnalysisResult { ActorToCommunity = AnalysisHelper.ActorToCommunity(network.Actors, communities), AnalyzedNetworkEdgeList = AnalysisHelper.EdgeList(network), CommunityList = AnalysisHelper.CommunityList(network.Actors, communities), Coverage = AnalysisHelper.Coverage(network, communities), Performance = AnalysisHelper.Performance(network, communities), Modularity = AnalysisHelper.Modularity(network, communities) }); }
public void HandleProtocolMessage(ClientType type, string connnectionId, string protocol) { BaseRequest request = AnalysisHelper.ToProtocol <BaseRequest>(protocol); switch (type) { case ClientType.WebClient: mWebClientService.HandleProtocol(connnectionId, request.ProtocolType, protocol); break; case ClientType.MobileClient: break; } }
/// <summary> /// Verifique se a imagem apresenta conteúdo não explícito /// </summary> /// <param name="classifyResult"></param> /// <returns></returns> private void ClassifyNotExplicitSex(DetailedResponse <ClassifiedImages> classifyResult) { var classifierClassPersonResult = classifyResult.GetClassifierClassResult(IBMImageClassifierEnum.NotExplicitSex); if (classifierClassPersonResult == null || classifierClassPersonResult.Score == null) { this.AddError("Não foi possivel classificar como conteúdo não explícito."); } var scoreRiskPerson = AnalysisHelper.GetScoreRisk(classifierClassPersonResult.Score.Value); if (scoreRiskPerson == ScoreRiskEnum.VeryLow || scoreRiskPerson == ScoreRiskEnum.Low) { this.AddError("Possivel conteúdo explícito na imagem."); } }
public void BasicRun() { AnalysisProgressHelperStub helperStub = new AnalysisProgressHelperStub(); AnalysisHelper ah = new AnalysisHelper(); ah.StartAnalysis(helperStub, controller, new ProjectFileTree()); Assert.That(helperStub.Count, Is.EqualTo(0)); Assert.That(helperStub.LastProgressObjectList.Count, Is.EqualTo(2)); AnalyseFilesProgress progress = (AnalyseFilesProgress)helperStub.LastProgressObjectList[1]; Assert.That(progress, Is.Not.Null); Assert.That(progress.NumberOfConflicts, Is.EqualTo(0)); Assert.That(progress.NumberOfResolved, Is.EqualTo(0)); Assert.That(progress.NumberOfExactCopies, Is.EqualTo(0)); }
private static ExcelContextForPhaseTwo <IAnalysisPhaseTwo> CreateExcelContext( AnalysisContext context) { IFunctionSelector goonessOfFit = AnalysisHelper.CreateGoodnessOfFit( context.GoodnessOfFit ); Func <ParametersPack, IAnalysisPhaseTwo> analysisFactory = args => AnalysisHelper.CreateAnalysisPhaseTwo(context.PhaseTwo, goonessOfFit, args); return(ExcelContextForPhaseTwo <IAnalysisPhaseTwo> .CreateFor( analysisContext : context, sheetName : ExcelHelper.CreateSheetName(PhaseNumber), analysisFactory : analysisFactory )); }
private static ExcelContextForPhaseOne <IAnalysisPhaseOnePartOne> CreateExcelContextPartOne( AnalysisContext context, int iterationNumber, int calculatedSampleSize) { Func <ParametersPack, IAnalysisPhaseOnePartOne> analysisFactory = args => AnalysisHelper.CreateAnalysisPhaseOnePartOne( context.PhaseOnePartOne, args ); return(ExcelContextForPhaseOne <IAnalysisPhaseOnePartOne> .CreateFor( args : context.Args.CreateWith(calculatedSampleSize), launchContext : context.LaunchContext, outputExcelFile : context.OutputExcelFile, sheetName : ExcelHelper.CreateSheetName(PhaseNumber, iterationNumber), analysisFactory : analysisFactory )); }
private static ExcelContextForPhaseOne <IAnalysisPhaseOnePartTwo> CreateExcelContextPartTwo( AnalysisContext context, AnalysisPhaseOnePartOneResult partOneResult) { string sheetName = ExcelHelper.CreateSheetName(PhaseNumber, partOneResult.TotalIterationNumber); Func <ParametersPack, IAnalysisPhaseOnePartTwo> analysisFactory = args => AnalysisHelper.CreateAnalysisPhaseOnePartTwo(context.PhaseOnePartTwo, args); return(ExcelContextForPhaseOne <IAnalysisPhaseOnePartTwo> .CreateFor( args : context.Args, launchContext : context.LaunchContext, outputExcelFile : context.OutputExcelFile, sheetName : sheetName, analysisFactory : analysisFactory )); }
public Result DeleteFaultDevice([FromBody] BatchDelete batchDelete) { var ids = batchDelete.ids; var data = ServerConfig.ApiDb.Query <FaultDevice>("SELECT * FROM `fault_device_repair` WHERE Id IN @id AND `State` != @state AND MarkedDelete = 0;", new { id = ids, state = RepairStateEnum.Complete }); if (data.Count() != ids.Count()) { return(Result.GenError <Result>(Error.FaultDeviceNotExist)); } FaultDeviceHelper.Cancel(ids); foreach (var d in data.GroupBy(x => x.FaultTime).Select(x => x.Key)) { AnalysisHelper.FaultCal(d); } return(Result.GenError <Result>(Error.Success)); }
public void Folder_And_File() { AnalysisProgressHelperStub helperStub = new AnalysisProgressHelperStub(); ProjectFileTree tree = new ProjectFileTree(); TextFileInformation tfi = new TextFileInformation(); tfi.RelativeFilePath = "Class.cs"; tfi.PrevGenFile = tfi.NewGenFile = tfi.UserFile = new TextFile("public class SomeClass { }"); tree.AddChildNode("folder").AddChildNode(tfi, "Class.cs"); AnalysisHelper ah = new AnalysisHelper(); ah.StartAnalysis(helperStub, controller, tree); Assert.That(tfi.CurrentDiffResult.DiffType, Is.EqualTo(TypeOfDiff.ExactCopy)); Assert.That(helperStub.Count, Is.EqualTo(0)); Assert.That(helperStub.LastProgressObjectList.Count, Is.EqualTo(4)); AnalyseFilesProgress progress = (AnalyseFilesProgress)helperStub.LastProgressObjectList[2]; Assert.That(progress, Is.Not.Null); Assert.That(progress.NumberOfConflicts, Is.EqualTo(0)); Assert.That(progress.NumberOfResolved, Is.EqualTo(0)); Assert.That(progress.NumberOfExactCopies, Is.EqualTo(0)); Assert.That(progress.ChangedFilePath, Is.EqualTo("folder\\Class.cs")); Assert.That(progress.ChangedFileStatus, Is.EqualTo(ProjectFileStatusEnum.Busy)); progress = (AnalyseFilesProgress)helperStub.LastProgressObjectList[3]; Assert.That(progress, Is.Not.Null); Assert.That(progress.NumberOfConflicts, Is.EqualTo(0)); Assert.That(progress.NumberOfResolved, Is.EqualTo(0)); Assert.That(progress.NumberOfExactCopies, Is.EqualTo(1)); Assert.That(progress.ChangedFilePath, Is.EqualTo("folder\\Class.cs")); Assert.That(progress.ChangedFileStatus, Is.EqualTo(ProjectFileStatusEnum.AnalysedFile)); string nl = Environment.NewLine; Assert.That(tfi.CalculateMergedFile(), Is.True); Assert.That(tfi.MergedFile.HasContents, Is.True); Assert.That(tfi.MergedFile.GetContents(), Is.EqualTo(nl + "public class SomeClass" + nl + "{" + nl + nl + "}")); }
public void GetScoreRisk() { var veryLow = 0.10f; var low = 0.30f; var medium = 0.50f; var high = 0.70f; var veryHigh = 0.90f; var veryLowScore = AnalysisHelper.GetScoreRisk(veryLow); var lowScore = AnalysisHelper.GetScoreRisk(low); var mediumScore = AnalysisHelper.GetScoreRisk(medium); var highScore = AnalysisHelper.GetScoreRisk(high); var veryHighScore = AnalysisHelper.GetScoreRisk(veryHigh); Assert.Equal(ScoreRiskEnum.VeryLow, veryLowScore); Assert.Equal(ScoreRiskEnum.Low, lowScore); Assert.Equal(ScoreRiskEnum.Medium, mediumScore); Assert.Equal(ScoreRiskEnum.High, highScore); Assert.Equal(ScoreRiskEnum.VeryHigh, veryHighScore); }
private Face GetBottomFace(Solid solid) { Face bottomFace = null; try { foreach (Face face in solid.Faces) { if (AnalysisHelper.DetermineFaceDirection(face, DisplayingFaces.Bottom)) { return(face); } } } catch (Exception ex) { MessageBox.Show("Failed to get a base face of the extruded solid. \n" + ex.Message, "FARCalculator:GetBottomFace", MessageBoxButtons.OK, MessageBoxIcon.Warning); } return(bottomFace); }
/// <summary> /// Verifique se a imagem apresenta conteúdo explícito /// </summary> /// <param name="clientCreditAnalysisModel"></param> /// <returns></returns> private DetailedResponse <ClassifiedImages> ClassifyExplicitSex(ClientCreditAnalysisModel clientCreditAnalysisModel) { var classifyPerson = this._ibmVisualRecognitionService.Classify(clientCreditAnalysisModel.FileUploadByte, IBMImageClassifierEnum.ExplicitSex); var classifierClassPersonResult = classifyPerson.GetClassifierClassResult(IBMImageClassifierEnum.ExplicitSex); ////Quando ele nao encontra, verifico a inversa if (classifierClassPersonResult == null || classifierClassPersonResult.Score == null) { this.ClassifyNotExplicitSex(classifyPerson); return(classifyPerson); } var scoreRiskPerson = AnalysisHelper.GetScoreRisk(classifierClassPersonResult.Score.Value); if (scoreRiskPerson == ScoreRiskEnum.VeryHigh || scoreRiskPerson == ScoreRiskEnum.High) { this.AddError("Possivel conteúdo explícito na imagem."); } return(classifyPerson); }
/// <summary> /// Verifique se na imagem possui uma pessoa /// </summary> /// <param name="clientCreditAnalysisModel"></param> /// <returns></returns> private DetailedResponse <ClassifiedImages> ClassifyPerson(ClientCreditAnalysisModel clientCreditAnalysisModel) { var classifyPerson = this._ibmVisualRecognitionService.Classify(clientCreditAnalysisModel.FileUploadByte, IBMImageClassifierEnum.Default); var classifierClassPersonResult = classifyPerson.GetClassifierClassResult(IBMImageClassifierEnum.Person); if (classifierClassPersonResult == null || classifierClassPersonResult.Score == null) { this.AddError("Não foi possivel classificar como pessoa."); return(classifyPerson); } var scoreRiskPerson = AnalysisHelper.GetScoreRisk(classifierClassPersonResult.Score.Value); if (scoreRiskPerson == ScoreRiskEnum.VeryLow || scoreRiskPerson == ScoreRiskEnum.Low) { this.AddError("Não foi possivel identificar a pessoa na imagem."); return(classifyPerson); } return(classifyPerson); }
public AnalysisResult Analyze(Network network, Dictionary <string, string> parameters) { var errors = ValidateParameters(network, parameters); if (errors.Count > 0) { // TODO: custom exception throw new ArgumentException(string.Join('\n', errors)); } var k = int.Parse(parameters["k"]); var communities = Algorithm.GetKCommunities(network, k); return(new AnalysisResult { ActorToCommunity = AnalysisHelper.ActorToCommunity(network.Actors, communities), AnalyzedNetworkEdgeList = AnalysisHelper.EdgeList(network), CommunityList = AnalysisHelper.CommunityList(network.Actors, communities), Coverage = AnalysisHelper.Coverage(network, communities), Performance = AnalysisHelper.Performance(network, communities), Modularity = AnalysisHelper.Modularity(network, communities) }); }
private Face CreateGeometry(Face bottomFace) { Face newFace = null; Solid extrusion = null; EdgeArrayArray edgeArrayArray = new EdgeArrayArray(); edgeArrayArray = bottomFace.EdgeLoops; List <Curve> curves = new List <Curve>(); foreach (EdgeArray edgeArray in edgeArrayArray) { foreach (Edge edge in edgeArray) { curves.Add(edge.AsCurve()); } CurveLoop profile = CurveLoop.Create(curves); List <CurveLoop> loops = new List <CurveLoop>(); loops.Add(profile); XYZ direction = new XYZ(0, 0, 1); extrusion = GeometryCreationUtilities.CreateExtrusionGeometry(loops, direction, 5); } if (null != extrusion) { foreach (Face face in extrusion.Faces) { if (AnalysisHelper.DetermineFaceDirection(face, DisplayingFaces.Bottom)) { newFace = face; } } } return(newFace); }
/// <summary> /// 网页开始抓取的入口 /// </summary> /// <returns></returns> public ActionResult StartCatch() { //实例化StreamReader var readerInput = new StreamReader(Request.InputStream); var javaser = new JavaScriptSerializer(); string s = readerInput.ReadToEnd(); var data = javaser.Deserialize <webUrl>(s); //把url网址转换成UTF-8编码格式 string url = HttpUtility.UrlDecode(data.url, Encoding.UTF8); foreach (var item in webRule_list) { //判断是否包含在数据库规则中 if (url.StartsWith(item.UrlWeb)) { if (item.Response == "json") { string datastr = ""; string method = "POST"; CatchHelper cathelp = new CatchHelper(); //判断是否是国家预警信息网 if (item.WebName == "alarm") { JObject jobect = Static.GetJson(item.RequestUrl, "GET", null); if (jobect == null) { return(null); } string path = Server.MapPath(System.Web.HttpContext.Current.Request.ApplicationPath.ToString()); FileStream file = new FileStream(path + @"Content\ThesaurusURL\city.txt", FileMode.Open, FileAccess.Read); StreamReader cityreader = new StreamReader(file, Encoding.GetEncoding("GBK")); string citystr = cityreader.ReadToEnd().Replace("\r", " ").Replace("\n", " "); List <string> citylist = citystr.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList(); List <BasicAttr> listbasic = new List <BasicAttr>(); foreach (var alarmitem in jobect["alertData"]) { BasicAttr basic = new BasicAttr(); basic.AttrName = alarmitem["headline"].ToString(); basic.Start_Time = basic.End_Time = alarmitem["sendTime"].ToString(); foreach (var city in citylist) { if (basic.AttrName.Contains(city)) { basic.Holding_City = city; if (city.Contains("市") || city.Contains("州") || city.Contains("区") || city.Contains("县")) { basic.Is_Influence_City = true; } else { basic.Is_Influence_Province = true; } break; } } listbasic.Add(basic); } db.BasicAttr.AddRange(listbasic); db.SaveChanges(); return(Json(new { ExecuteResult = listbasic.Count, Success = "fail" })); } if (item.WebName == "damai") { if (url.Contains("演唱会")) { datastr = "ctl=演唱会&currPage="; } if (url.Contains("体育比赛")) { datastr = "ctl=体育比赛&currPage="; } for (int i = 1; i < 100; i++) { //获取请求链接返回的json对象 JObject jobject = Static.GetJson(item.RequestUrl, method, datastr + i); List <Concert> listconvert = new List <Concert>(); //把jobject对象数据整理到数据库 if (jobject != null) { listconvert = cathelp.FConcertJsonToList(jobject, item.WebName); } else { return(Json(new { ExecuteResult = "基础连接已经关闭", Success = "fail" })); } //listconvert为空代表数据已经抓完 if (listconvert == null) { return(Json(new { ExecuteResult = "success", Success = "success" })); } } } if (item.WebName == "yongle") { datastr = "j=1&p="; method = "GET"; item.RequestUrl = url; for (int i = 1; i < 100; i++) { //获取请求链接返回的json对象 JObject jobject = Static.GetJson(item.RequestUrl, method, datastr + i); List <Concert> listconvert = new List <Concert>(); //把jobject对象数据整理到数据库 if (jobject != null) { listconvert = cathelp.FConcertJsonToList(jobject, item.WebName); } else { return(Json(new { ExecuteResult = "基础连接已经关闭", Success = "fail" })); } //listconvert为空代表数据已经抓完 if (listconvert == null) { return(Json(new { ExecuteResult = "success", Success = "success" })); } } } } if (item.Response == "html") { //判断是否是E展会 if (item.WebName == "E") { //实例化对象 WaitCatchLink = new Queue <string>(); CatchedLink = new List <string>(); //获取编码 string encoding = Static.GetEncoding(url); //如果获取源码失败则默认使用UTF-8编码 if (encoding == null) { encoding = "UTF-8"; } //获取网页源码 string html = Static.GetHtml(item.RequestUrl, Encoding.GetEncoding(encoding), "POST", "serarchwhere={1:1}&SearType=1&page=1"); if (html == null) { return(Json(new { ExecuteResult = "fail", success = "fail" })); } //获取该抓取的网页页数 int page = Static.GetPageCount(html, item.PageXpath); for (int i = 1; i < page; i++) { //获取网页源码 html = Static.GetHtml(item.RequestUrl, Encoding.GetEncoding(encoding), "POST", "serarchwhere={1:1}&SearType=1&page=" + i); HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(html); //获取指定Xpath路径的所有链接 HtmlNodeCollection nodecollection = doc.DocumentNode.SelectSingleNode(item.WebContentXpath).SelectNodes(".//a[@href]"); if (nodecollection == null) { continue; } foreach (HtmlNode nodelink in nodecollection) { //获取集合中的一条链接 string newlink = nodelink.Attributes["href"].Value; //判断链接的有效性 if (newlink == "" || newlink == "#" || newlink == "javascript") { continue; } //补全子链接 if (newlink.StartsWith("/") && !newlink.StartsWith("//")) { newlink = item.UrlWeb.TrimEnd('/') + newlink; } //判断该链接是否已经抓取过或者已经在等待抓取队列中 if (newlink.StartsWith(item.UrlWeb) && !WaitCatchLink.Contains(newlink) && !CatchedLink.Contains(newlink)) { WaitCatchLink.Enqueue(newlink); } } //实例化基础属性类 List <BasicAttr> listbasic = new List <BasicAttr>(); while (WaitCatchLink.Count > 0) { //取出等待抓取链接队列中的第一条链接并移除 string catchlink = WaitCatchLink.Dequeue(); //把次链接添加到已经抓取的集合中 CatchedLink.Add(catchlink); //获取此链接的源码 string catchhtml = Static.GetHtml(catchlink, Encoding.GetEncoding(encoding), null, null); //如果源码没有抓取成功则跳过此链接 if (catchhtml == null) { continue; } doc = new HtmlDocument(); doc.LoadHtml(catchhtml); //根据给定的Xpath路径获取内容节点 HtmlNode contentnode = doc.DocumentNode.SelectSingleNode(item.AttrContentXpath); if (contentnode == null) { continue; } AnalysisHelper analy = new AnalysisHelper(); string serverpath = Server.MapPath(System.Web.HttpContext.Current.Request.ApplicationPath.ToString()); BasicAttr ba = analy.Analysis(contentnode.InnerText, serverpath); listbasic.Add(ba); } //把处理好的事件属性添加到数据库中 db.BasicAttr.AddRange(listbasic); //保存数据 db.SaveChanges(); } return(Json(new { ExecuteResult = CatchedLink.Count, Success = "success" })); } //判读是否是中国会展门户 if (item.WebName == "cnena") { DateTime dt = DateTime.Now; //实例化对象 WaitCatchLink = new Queue <string>(); CatchedLink = new List <string>(); string encoding = Static.GetEncoding(url); //如果获取源码失败则默认使用UTF-8编码 if (encoding == null) { encoding = "UTF-8"; } //默认抓取未来七天内开始的展会 DateTime dtseven = dt.AddDays(7); //用于判断该链接的内容是否在指定的抓取的时间段内 bool Isoverdue = false; int[] Monthtime; //判断是否应该抓取下一个月的数据 if (dtseven.Month > dt.Month) { Monthtime = new int[] { dt.Month, dtseven.Month } } ; else { Monthtime = new int[] { dt.Month } }; foreach (var month in Monthtime) { for (int i = 1; i < 100; i++) { string requesturl = item.RequestUrl + "?daytime=" + month + "&page=" + i; string html = Static.GetHtml(requesturl, Encoding.GetEncoding(encoding), null, null); //判断是否成功获取网页源码 if (html == null) { continue; } HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(html); //根据给定的Xpath路径获取内容节点 HtmlNode hn = doc.DocumentNode.SelectSingleNode(item.WebContentXpath); //判断是否成功获取该节点 if (hn == null) { continue; } foreach (var cnenatable in hn.SelectNodes("table")) { Match math = Regex.Match(cnenatable.InnerText, @"(\d{4}|\d{2})(\-|\/|\\)\d{1,2}(\-|\/|\\)\d{1,2}(\s?\d{2}:\d{2})?", RegexOptions.IgnoreCase); if (math.Success) { DateTime dd = Convert.ToDateTime(math.Groups[0].Value).Date; if (dd > dt && dd < dtseven) { foreach (var cnenalink in cnenatable.SelectNodes(".//td[2]")) { string linktext = item.UrlWeb.TrimEnd('/') + "/" + cnenalink.SelectSingleNode(".//a[@href]").Attributes["href"].Value; if (linktext == "") { continue; } if (!WaitCatchLink.Contains(linktext) && !CatchedLink.Contains(linktext)) { WaitCatchLink.Enqueue(linktext); continue; } } } if (dd < dt) { Isoverdue = true; break; } } } List <BasicAttr> listbasic = new List <BasicAttr>(); while (WaitCatchLink.Count > 0) { //取出等待抓取链接队列中的第一条链接并移除 string catchlink = WaitCatchLink.Dequeue(); //把次链接添加到已经抓取的集合中 CatchedLink.Add(catchlink); //获取此链接的源码 string catchhtml = Static.GetHtml(catchlink, Encoding.GetEncoding(encoding), null, null); //如果源码没有抓取成功则跳过此链接 if (catchhtml == null) { continue; } doc = new HtmlDocument(); doc.LoadHtml(catchhtml); //根据给定的Xpath路径获取内容节点 HtmlNode contentnode = doc.DocumentNode.SelectSingleNode(item.AttrContentXpath); if (contentnode == null) { continue; } AnalysisHelper analy = new AnalysisHelper(); string serverpath = Server.MapPath(System.Web.HttpContext.Current.Request.ApplicationPath.ToString()); BasicAttr ba = analy.Analysis(contentnode.InnerText, serverpath); listbasic.Add(ba); } if (Isoverdue) { break; } } } return(Json(new { ExecuteResult = CatchedLink.Count, Success = "success" })); } //判读是否中国天气预警 if (item.WebName == "tianqialarm") { //实例化对象 WaitCatchLink = new Queue <string>(); CatchedLink = new List <string>(); //获取网页编码 string encoding = Static.GetEncoding(url); //如果获取源码失败则默认使用UTF-8编码 if (encoding == null) { encoding = "UTF-8"; } //用于判断该链接的内容是否在指定的抓取的时间段内 bool Isoverdue = false; for (int i = 1; i < 100; i++) { //补全请求链接 string requesturl = item.RequestUrl.TrimEnd('/') + @"/" + i + @"/"; //获取网页编码 string html = Static.GetHtml(requesturl, Encoding.GetEncoding(encoding), null, null); //判断是否成功获取网页源码 if (html == null) { continue; } HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(html); //根据给定的Xpath路径获取内容节点 HtmlNode hn = doc.DocumentNode.SelectSingleNode(item.WebContentXpath); //判断是否成功获取该节点 if (hn == null) { continue; } //存放网页所有的时间 List <DateTime> listtime = new List <DateTime>(); //匹配该网页中所有符合条件的时间存到集合match中 MatchCollection match = Regex.Matches( hn.InnerText, @"(\d{4}|\d{2})(\-|\/|\\)\d{1,2}(\-|\/|\\)\d{1,2}(\s?\d{2}:\d{2})?", RegexOptions.IgnoreCase); if (match.Count > 0) { string dateStr = ""; for (int j = 0; j < match.Count; j++) { dateStr = match[j].Value; try { listtime.Add(Convert.ToDateTime(dateStr)); } catch { continue; } } } //获取该节点的链接存到集合hc中 HtmlNodeCollection hc = hn.SelectNodes(".//a[@href]"); for (int n = 0; n < hc.Count; n++) { //获取第n个链接 string tianqilink = hc[n].Attributes["href"].Value; //获取当前时间 DateTime dt = DateTime.Now.Date; //判断该链接的日期是否是在当前日期段内 if (listtime[n].Date >= dt) { if (!WaitCatchLink.Contains(tianqilink) && !CatchedLink.Contains(tianqilink)) { WaitCatchLink.Enqueue(tianqilink); } else { continue; } } else { Isoverdue = true; //已经超过指定的时间段 } } List <BasicAttr> listbasic = new List <BasicAttr>(); while (WaitCatchLink.Count > 0) { //取出等待抓取链接队列中的第一条链接并移除 string catchlink = WaitCatchLink.Dequeue(); //把次链接添加到已经抓取的集合中 CatchedLink.Add(catchlink); //获取此链接的源码 string catchhtml = Static.GetHtml(catchlink, Encoding.GetEncoding(encoding), null, null); //如果源码没有抓取成功则跳过此链接 if (catchhtml == null) { continue; } doc = new HtmlDocument(); doc.LoadHtml(catchhtml); //根据给定的Xpath路径获取内容节点 HtmlNode contentnode = doc.DocumentNode.SelectSingleNode(item.AttrContentXpath); if (contentnode == null) { continue; } AnalysisHelper analy = new AnalysisHelper(); string serverpath = Server.MapPath(System.Web.HttpContext.Current.Request.ApplicationPath.ToString()); BasicAttr ba = analy.Analysis(contentnode.InnerText, serverpath); listbasic.Add(ba); } //判断是否已经超过指定的时间段 if (Isoverdue) { break; } } return(Json(new { ExecuteResult = CatchedLink.Count, Success = "success" })); } } } } return(Json(new { ExecuteResult = "该链接未包含在规则表中", Success = "success" })); }
public static void Init(IConfiguration configuration) { RedisHelper.Init(configuration); RedisHelper.CloseWrite = _close; ServerId = configuration.GetAppSettings <int>("ServerId"); IsAnalysis = configuration.GetAppSettings <bool>("Analysis"); ApiDb = new DataBase(configuration.GetConnectionString("ApiDb")) { CloseWrite = _close }; _loads = new Dictionary <string, Action> { //{PermissionHelper.TableName, PermissionHelper.LoadConfig}, { "ReadDB", LoadDateBase }, { PermissionHelper.TableName, PermissionHelper.LoadConfig }, { PermissionGroupHelper.TableName, PermissionGroupHelper.LoadConfig }, { NpcProxyLinkServerHelper.TableName, NpcProxyLinkServerHelper.LoadConfig }, }; foreach (var action in _loads.Values) { action(); } GateUrl = configuration.GetAppSettings <string>("GateUrl"); ErpUrl = configuration.GetAppSettings <string>("ErpUrl"); GlobalConfig.LoadGlobalConfig(); AccountInfoHelper.Init(configuration); WorkFlowHelper.Init(); OldWorkFlowHelper.Init(); //HMaterialHelper.MaterialChange3(); //return; if (ServerId == 1) { HKanBanHelper.Init(); } else if (ServerId == 2) { HNotifyHelper.Init(); HWarningHelper.Init(); HOpScheduleHelper.Init(); //HFlowCardHelper.Init(); //SimulateHelper.Init(); HScheduleHelper.Init(); TimerHelper.Init(); //HMaterialHelper.Init(); } else if (ServerId == 3) { AnalysisHelper.Init(); HKanBanHelper.Init(); } if (!RedisHelper.Exists(IsSetProcessDataKey)) { RedisHelper.SetForever(IsSetProcessDataKey, 1); } if (!RedisHelper.Exists(IsSetDataIgnoreKey)) { RedisHelper.SetForever(IsSetDataIgnoreKey, 0); } _loads.Add(HWarningHelper.RedisReloadKey, HWarningHelper.NeedReload); _loads.Add(HOpScheduleHelper.RedisReloadKey, HOpScheduleHelper.NeedReload); Log.InfoFormat("ServerConfig Done"); }
protected static string GetGuid() { return(AnalysisHelper.GetGuid()); }
protected static string DecodeString(string value, Dictionary <string, string> placeholders) { return(AnalysisHelper.DecodeString(value, placeholders)); }
protected static string EncodeString(string value, out Dictionary <string, string> placeholders) { return(AnalysisHelper.EncodeString(value, out placeholders)); }