public Search(Query query) { Query = query; ResultList = new List<QrelLine>(); Connector conn = new Connector(); List<Paragraph> paragraphs = conn.GetParagraph(query.Terms.Values.ToList()); foreach (Paragraph paragraph in paragraphs) { String path = paragraph.Parent.Path; String xpath = paragraph.Xpath; Double relevance = paragraph.Relevance; ResultList.Add(new QrelLine(path, xpath, relevance)); } ResultList = ResultList.OrderByDescending(v => v.Relevance).ToList(); StringBuilder result = new StringBuilder(); foreach (QrelLine qrelLine in ResultList) { String path = qrelLine.DocPath; String xpath = qrelLine.XmlPath; Double relevance = qrelLine.Relevance; result.AppendLine("[" + relevance + "] " + path + " - " + xpath); } Result = result.ToString(); }
private void UpdateDataTablesFromApi(Connector connector) { // TODO divide this big function? // updating users ... Console.Write("Updating users..."); var userController = new UsersController(connector.mySqlConnection); var rateableUsers = userController.GetRateableUsers(); var friends = new List<string>(); foreach (string user in rateableUsers) { userController.FindAndInsertNewFriends(GetFriends(user)); } Console.Write(" [DONE]\n"); // searching for update... var usersForUpdate = userController.GetUsersWithOldUpdate(); while (usersForUpdate != null) { break; // TODO 1: get for each user Dictionary<artist, number of songs> // TODO 1.1: fill "counts" table, if artist appeared for the 1st time, add him to "artists" table // TODO 2: check. (GetUsersWithOldUpdate again) } }
public AnalysisStatisticForm(List<string> words, Connector.Redmine.Model.Issue task) { InitializeComponent(); Logger.TextChanged += (sender, e) => { resultTextBox.Text = e; }; resultTextBox.TextChanged += (sender, e) => { resultTextBox.SelectionStart = resultTextBox.TextLength; resultTextBox.ScrollToCaret(); }; _words = words; _task = task; Logger.LogHtml("<h1>Статистический анализ</h1>"); Logger.LogText("Статистический анализ"); // get frequency of words var freqLib = new TA.Statistic.Frequency(_words); var orderedWords = freqLib.Process().OrderByDescending(i => i.count); // log it Logger.LogHtml("<h2>Частота употребления слов</h2><ul>"); Logger.LogText("ЧАСТОТА УПОТРЕБЛЕНИЯ СЛОВ:"); foreach (var item in orderedWords) { Logger.LogHtml(string.Format("<li><strong>{0}</strong> — {1}</li>", item.word, item.count)); Logger.LogText(string.Format(" {0} — {1}", item.word, item.count)); } resultTextBox.Text += "\r\n"; Logger.LogHtml("</ul>"); }
RSSPub(string serverUrl) { m_Connector = new Connector(); Parameters p = new Parameters(); p.ServerUrl = serverUrl; m_Connector.Open(p); }
//saves the information of the Kid and return the ID from the database public string SaveInfo(string Server="") { Connector js; if(Server=="") { js = new Connector(); } else { js = new Connector(Server, "Kids_Checkin", "kidschurch", "1nt3gr1ty@ENLI"); } string fldPicture = this.FirstName + this.LastName + ".jpg"; this.img.Save(js.GetPath() + "/Kids/" + fldPicture); string q = "INSERT INTO tblKids(fldStudentID,fldFirstName,fldLastName,fldNickName,fldBirthday,fldChurch,fldDateCreated,fldPicture,fldGender,fldAllergies)" + " VALUES('" + this.StudentID + "','" + this.FirstName + "','" + this.LastName + "','" + this.NickName + "','" + this.BirthDay + "','" + this.ChurchID + "','" + DateTime.Now.ToShortDateString() + "','" + fldPicture + "','" + this.Gender + "','" + this.Allergies + "')"; js.ExecuteNonQuery(q); q = "SELECT fldID FROM tblKids WHERE fldStudentID='" + this.StudentID + "'"; js.ExecuteQuery(q); js.RiD.Read(); return js.RiD["fldID"].ToString(); }
public static string enable(string pluginid, Connector conn) { string basePath = Misc.Plugins.getPluginBasePath(pluginid, conn); // Install content Misc.Plugins.contentInstall(basePath + "\\Content"); return null; }
private void btn_connect_Click(object sender, EventArgs e) { // Initialize a new Connector and add event handlers connector = new Connector(); connector.DeviceConnected += new EventHandler(OnDeviceConnected); connector.DeviceFound += new EventHandler(OnDeviceFound); connector.DeviceConnectFail += new EventHandler(OnDeviceFail); connector.DeviceDisconnected += new EventHandler(OnDeviceDisconnected); // Scan for devices across COM ports // The COM port named will be the first COM port that is checked. //string COM12 = null; connector.ConnectScan("COM40"); //Thread.Sleep(45000); if (true) { progressBar2.Value = 0; Thread.Sleep(2000); progressBar2.Value = 20; Thread.Sleep(2000); progressBar2.Value = 40; Thread.Sleep(2000); progressBar2.Value = 60; Thread.Sleep(2000); progressBar2.Value = 80; Thread.Sleep(2000); progressBar2.Value = 100; } }
internal SetConnectorPointsCommand(Connector connector, List<KeyValuePair<double, double>> edgePoints) { Debug.Assert(connector != null, "connector is null"); _connector = connector; _edgePoints = edgePoints; }
//saves the information of the Fetcher and return the ID from the database public string SaveInfo(string Server = "") { Connector js; if (Server == "") { js = new Connector(); } else { js = new Connector(Server, "Kids_Checkin", "kidchurch", "1nt3gr1ty@ENLI"); } string fldPicture = this.FirstName + this.LastName + ".jpg"; this.Image.Save(js.GetPath() + "/Fetchers/" + fldPicture); string q = "INSERT INTO tblFetcher(fldFirstName,fldLastName,fldContactDetails,fldRelationship,fldPicture,fldEmail)" + " VALUES('" + this.FirstName + "','" + this.LastName + "','" + this.ContactID + "','" + this.Relationship + "','" + fldPicture + "','" + this.Email + "')"; js.ExecuteNonQuery(q); q = "SELECT fldID FROM tblFetcher WHERE fldLastName='" + this.LastName + "' AND fldFirstName ='" + this.FirstName + "' AND fldPicture='" + fldPicture + "'"; js.ExecuteQuery(q); js.RiD.Read(); return js.RiD["fldID"].ToString(); }
static void Main(string[] args) { // // TODO: Add code to start application here // if (args.Length != 2) { Console.WriteLine("Wrong number of arguments. Got {0} instead.", args.Length); return; } MyHandler myH = new MyHandler(); Parameters p = new Parameters(); p.ServerUrl = args[0]; Connector c = new Connector(); if (c.Open(p)) { Message m = new Message(); m.Set("do_method", "notify"); m.Set("kn_to", args[1]); m.Set("kn_payload", "Hello"); m.Set("nickname", "dotnet"); m.Set("kn_response_format", "simple"); c.Publish(m, myH); c.Close(); } }
private List<string> _roles; //Коллекция ролей пользователя. Служит для снижения нагрузки на базу данных при частых вызовах методов DataFeed() { _context = new EFDbContext(); operationContext = OperationContext.Current; operationContext.Channel.Opened += Channel_Opened; operationContext.Channel.Closed += Channel_Closed; info = new Info(); _uManager = new UManager(new UserStore<User>(new IdentityContext())); _user = _uManager.FindByName(operationContext.ServiceSecurityContext.PrimaryIdentity.Name); //Получаем текущего Identity пользователя var roles = _uManager.GetUserRoles(_user.Id); //Создадим список ролей пользователя к которым будем обращаться в методах для проверки, чтобы не загружать БД лишними запросами. _roles = roles.Select(r => r.Name).ToList(); _conCount = roles.Max(r => r.NumberOfThreads); //Установить максимальное количество потоков доступное из ролей данному пользователю _connector = GetAvialableConnector(); _connector.ValuesChanged += Level1Changed; _connector.MarketDepthsChanged += Level2Changed; _connector.NewNews += NewNews; _connector.Error += Error; Console.WriteLine("SID: {0} ", operationContext.Channel.SessionId); _listener = new Listener(operationContext); //Запускаем вторичные потоки для обработки исторических данных for (int i = 0; i < _conCount; i++) { new Task(_listener.CandlesQueueStart).Start(); } }
static void Main(string[] args) { NetConfig.LatencySimulation = true; Connector client = new Connector("Sample1.1", false); Clock fastClock = new Clock(0.02f); Clock slowClock = new Clock(1.0f); fastClock.OnFixedUpdate += SendPayload; slowClock.OnFixedUpdate += SendNotification; Program.peer = client.Connect("127.0.0.1:42324"); while (true) { fastClock.Tick(); slowClock.Tick(); client.Update(); if (Console.KeyAvailable) { ConsoleKeyInfo key = Console.ReadKey(true); switch (key.Key) { case ConsoleKey.F1: client.Stop(); return; default: break; } } } }
public static Schema BuildSchema(Connector connector, GetSupportedObjectClassesDelegate getSupportedObjectClassesDelegate, GetObjectClassInfoDelegate getObjectClassInfoDelegate, GetSupportedOperationsDelegate getSupportedOperationsDelegate, GetUnSupportedOperationsDelegate getUnSupportedOperationsDelegate) { SchemaBuilder schemaBuilder = new SchemaBuilder(SafeType<Connector>.Get(connector)); //iterate through supported object classes foreach (ObjectClass oc in getSupportedObjectClassesDelegate()) { ObjectClassInfo ocInfo = getObjectClassInfoDelegate(oc); Assertions.NullCheck(ocInfo, "ocInfo"); //add object class to schema schemaBuilder.DefineObjectClass(ocInfo); //add supported operations IList<SafeType<SPIOperation>> supportedOps = getSupportedOperationsDelegate(oc); if (supportedOps != null) { foreach (SafeType<SPIOperation> op in supportedOps) { schemaBuilder.AddSupportedObjectClass(op, ocInfo); } } //remove unsupported operatons IList<SafeType<SPIOperation>> unSupportedOps = getUnSupportedOperationsDelegate(oc); if (unSupportedOps != null) { foreach (SafeType<SPIOperation> op in unSupportedOps) { schemaBuilder.RemoveSupportedObjectClass(op, ocInfo); } } } LOGGER.TraceEvent(TraceEventType.Verbose, CAT_DEFAULT, "Finished retrieving schema"); return schemaBuilder.Build(); }
private static Transaction.TransactionStatus RequestTransactionStatus(string transactionId, OrderInfo order) { try { var connector = new Connector(); // Override MerchantId loaded from configuration //connector.MerchantId = "025152899"; var transaction = connector.RequestTransactionStatus(transactionId); var acquirerId = transaction.AcquirerId; var status = transaction.Status; var consumerName = transaction.ConsumerName; var fingerprint = transaction.Fingerprint; var consumerIBAN = transaction.ConsumerIBAN; var consumerBIC = transaction.ConsumerBIC; var amount = transaction.Amount; var currency = transaction.Currency; var signatureString = ByteArrayToHexString(transaction.SignatureValue); // Place newlines in Hex String for (int i = 256; i > 0; i -= 32) signatureString = signatureString.Substring(0, i) + "<br />" + signatureString.Substring(i); var signatureValue = signatureString; return status; } catch (IDealException ex) { Log.Instance.LogError("ING Advanced PaymentRequestHander: " + ex); } return Transaction.TransactionStatus.Failure; }
public ConnectionEventArgs(Connection connection, bool manual) { this.connection=connection; this.to=connection.To; this.from=connection.From; this.manual = manual; }
/// <summary> /// Init all roots and configs /// </summary> void InitFuc() { Application.runInBackground = playInBackGround; Debuger.EnableLog = enableDebuger; manager = this.gameObject.AddComponent<SceneManager>(); manager.cacheRoot = transform.FindChild("CacheRoot"); manager.uiRoot = transform.FindChild("UI Root"); manager.senceRoot = transform.FindChild("SceneRoot"); manager.playerRoot = transform.FindChild("PlayerRoot"); manager.ghostRoot = transform.FindChild("GhostRoot"); uicamera = manager.uiRoot.FindChild("Camera").GetComponent<UICamera>(); tool = this.gameObject.AddComponent<Utility>(); connector = this.gameObject.AddComponent<Connector>(); this.gameObject.AddComponent<CacheFactory>(); ConfigFactory.InitResourceConfig(); ConfigFactory.ReadSystemConfig(); this.gameObject.AddComponent<ConfigInfo>(); ConfigInfo.ReadUIRules(); GUIManager.instance.Loading.gameObject.SetActive(true); GUIManager.instance.FloatMessagePanel.gameObject.SetActive(true); GUIManager.instance.FloatTip.gameObject.SetActive(true); GUIManager.LoadingPercent(10); ConfigInfo.Init(); ConfigInfo.InitPreGameConfigs(); GUIManager.FinishLoading(); StartGame(); }
/// <summary> /// Метод подписывает пользователя на получение новых значений Level1. /// Могут использовать только пользователи с ролями: "Level1", "Level2" и "Admin". /// </summary> /// <param name="security"></param> public static FaultException SubscribeLevel1(Connector connector, Security security, List<string> roles) { string[] rolesPermission = { "Level1", "Level2", "Admin" }; //Доступно ролям. if (rolesPermission.Intersect(roles).Any()) { if (security != null) { var criteria = new StockSharp.BusinessEntities.Security { Code = security.Ticker, Id = security.Code, Board = StockSharp.BusinessEntities.ExchangeBoard.Nyse }; //Регистрируем инструмент для получения Level1 connector.RegisterSecurity(criteria); Console.WriteLine("Register SECURITY {0}, {1}", connector.ConnectionState, connector.Id); } else { return new FaultException("Значение инструмента не может быть неопределенным."); } } else { return new FaultException("Level1 недоступен для этого аккаунта."); } return null; }
public Connection(Connector source, Connector sink) { this.ID = Guid.NewGuid(); this.Source = source; this.Sink = sink; base.Unloaded += new RoutedEventHandler(Connection_Unloaded); }
static void Main(string[] args) { Connector server = new Connector("Sample1.1", true); server.Host(42324); while (true) { server.Update(); if (Console.KeyAvailable) { ConsoleKeyInfo key = Console.ReadKey(true); switch (key.Key) { case ConsoleKey.F1: server.Stop(); return; default: break; } } } }
public static void requestEnd(string pluginid, Connector conn, ref Misc.PageElements pageElements, HttpRequest request, HttpResponse response) { bool cookiesEnabled = request.Cookies["cookie-control"] != null; // Add styling and toggle button Misc.Plugins.addHeaderCSS(pageElements["URL"] + "/Content/CSS/CookieControl.css", ref pageElements); Misc.Plugins.addHeaderJS(pageElements["URL"] + "/Content/JS/CookieControl.js", ref pageElements); // Add toggle button pageElements.appendToKey("BODY_FOOTER", Core.templates["cookiecontrol"]["toggle"]); // Add warning banner if (!cookiesEnabled) pageElements.appendToKey("BODY_HEADER", Core.templates["cookiecontrol"]["banner"]); else { // Check if cookies have been enabled, if so return - no need to remove cookies pageElements.setFlag("COOKIES_ON"); return; } // Clear all the response cookies - these may have been added programmatically response.Cookies.Clear(); // Add each cookie, sent in the request, in the response - to expire HttpCookie cookie; for (int i = 0; i < request.Cookies.Count; i++) { cookie = request.Cookies[i]; if (cookie.Name != "ASP.NET_SessionId") { cookie.Expires = DateTime.Now.AddDays(-2); response.Cookies.Add(cookie); } } }
/// <summary> /// Creates a new subitem used to visualise a connected child on the node. /// </summary> /// <param name="connector">The connector we want to visualise.</param> /// <param name="child">The child represented by the subitem. Can be null.</param> /// <param name="index">The index of the child in the connector. Also a null child has an index!</param> public SubItemConnector(Connector connector, BaseNode child, int index) : base(null, null, __font, Brushes.White, Alignment.Right, true) { _connector = connector; _child = child; _index = index; }
//Instance of object which contains configuration for sending data. //ULoader_JSON config; //Instacje of object which sends data. //USender uSender; public MainWindow() { InitializeComponent(); attentionValuesCollection = new DataCollection(); var attentionDataSource = new EnumerableDataSource<Data>(attentionValuesCollection); attentionDataSource.SetXMapping(x => dateAttention.ConvertToDouble(x.Date)); attentionDataSource.SetYMapping(y => y.Value); plotterAttention.AddLineGraph(attentionDataSource, Colors.Red, 2, "Attetion"); connector = new Connector(); connector.DeviceConnected += new EventHandler(OnDeviceConnected); connector.DeviceConnectFail += new EventHandler(OnDeviceFail); connector.DeviceValidating += new EventHandler(OnDeviceValidating); connector.ConnectScan("COM3"); //Stworzenie obiektu typu Random do wyboru losowego słowa ze słownika. randomWordNumber = new Random(); wordNumber = 0; attentionComingCounter = 0; attentionValueSum = 0; puzzlesSolved = 0; wordStatList = new List<WordStat>(); currentWord = ""; //config = new ULoader_JSON(@"..\..\config.json"); //uSender = config.GetSender("output1"); }
public Connection(Connector source, Connector sink, ConnectionViewModel connectionViewModel) { ID = Guid.NewGuid(); Source = source; Sink = sink; ConnectionViewModel = connectionViewModel; //Unloaded += Connection_Unloaded; }
public Form2() { connector = new Connector(); connector.DeviceConnected += new EventHandler(OnDeviceConnected); connector.Connect("COM31"); InitializeComponent(); }
public void Initialize() { _configurationSettings = A.Fake<Intuition.Configuration.ISettings>(); _deviceFactory = A.Fake<Intuition.Gateway.IFactory>(); _clientEndpoint = A.Fake<Messaging.Client.IEndpoint>(); _subject = new Connector(_clientEndpoint, _configurationSettings, _deviceFactory); }
public connect(game game) { connector = new Connector(); connector.ConnectedEvent += new ConnectedHandler(connector_ConnectedEvent); connector.Connect("127.0.0.1",59398); gamee = game; return; }
public void testConstructor() { TestUtil.INIT_TESTCASE("testConstructor"); Connector c1 = new Connector(); Assertion.Assert("!c1.IsConnected()", !c1.IsConnected()); }
public bool Equals(Connector ctr) { // If parameter is null return false: if ((object)ctr == null) { return false; } // Return true if the fields match: return (this.A == ctr.A && this.B == ctr.B) || (this.A == ctr.B && this.B == ctr.A); }
private LuminexSDK() { var connect = new Connector(); objLXIS = connect.Application["A0095978-3906-4ba5-AC19-3DE880EE6A01"]; if(objLXIS == null) { throw new Exception("Cannot connect to the Luminex IS App!"); } }
public ConnectorAdorner(DesignerCanvas designer, Connector sourceConnector) : base(designer) { designerCanvas = designer; this.sourceConnector = sourceConnector; drawingPen = new Pen(Brushes.LightSlateGray, 1); drawingPen.LineJoin = PenLineJoin.Round; Cursor = Cursors.Cross; }
public void Delete_in_transaction() { int[] accountIds = null; using (var connector = new Connector(_clientConfig)) { var accounts = connector.DataSource <Account>(); accountIds = connector.GenerateUniqueIds("account_id", 2); var tIds = connector.GenerateUniqueIds("transfer_ids", 2); accounts.Put(new Account { Id = accountIds[0], Balance = 1000 }); accounts.Put(new Account { Id = accountIds[1], Balance = 0 }); // make a many transfer between two accounts { var transferredMoney = 334; var transaction = connector.BeginTransaction(); transaction.UpdateIf(new Account { Id = accountIds[0], Balance = 1000 - transferredMoney }, account => account.Balance >= transferredMoney); transaction.Put(new Account { Id = accountIds[1], Balance = transferredMoney }); transaction.Put(new MoneyTransfer { Id = tIds[0], Amount = transferredMoney, SourceAccount = accountIds[0], DestinationAccount = accountIds[1] }); transaction.Commit(); // check that everything is updated in memory var src = accounts[accountIds[0]]; var dst = accounts[accountIds[1]]; Assert.AreEqual(666, src.Balance); Assert.AreEqual(334, dst.Balance); var transfers = connector.DataSource <MoneyTransfer>(); var transfer = transfers.Single(); Assert.AreEqual(334, transfer.Amount); Assert.AreEqual(334, transfer.Amount); } // then cancel the transfer { var transfers = connector.DataSource <MoneyTransfer>(); var transfer = transfers.Single(); var transaction = connector.BeginTransaction(); transaction.Put(new Account { Id = accountIds[0], Balance = 1000 }); transaction.Put(new Account { Id = accountIds[1], Balance = 0 }); transaction.Delete(transfer); transaction.Commit(); // check that everything is updated in memory var src = accounts[accountIds[0]]; var dst = accounts[accountIds[1]]; Assert.AreEqual(1000, src.Balance); Assert.AreEqual(0, dst.Balance); // no more transfer var transferCount = transfers.Count(); Assert.AreEqual(0, transferCount); } } // check that everything is persisted ok using (var connector = new Connector(_clientConfig)) { var accounts = connector.DataSource <Account>(); var src = accounts[accountIds[0]]; var dst = accounts[accountIds[1]]; Assert.AreEqual(1000, src.Balance); Assert.AreEqual(0, dst.Balance); var transfers = connector.DataSource <MoneyTransfer>(); Assert.AreEqual(0, transfers.Count()); } }
/// <summary> /// Default constructor. /// </summary> public DirectoryEngineG(Connector connector) { Connector = connector; Filer = new FilerG(Connector); }
private void ProcessProductGroups( PetaPoco.Database pDb, Connector connector, List <Content> content, List <ProductGroupMapping> productGroupMappings, FilterInfo filter, ProductGroupMapping parent, List <ContentProductGroup> contentProductGroups, List <ContentProductGroup> newContentProductGroupsToInsertInDb ) { if (filter.Flatten) { if (parent == null) { log.WarnFormat("FlattenHierarchy is not supported on root mappings"); return; } //combine all child groups into this one List <int> childIDList = productGroupMappings.Select(x => x.ProductGroupID).ToList(); //recursive? var groupProducts = content.AsQueryable(); if (parent.FilterByParentGroup) { if (filter.ProductGroupFilter.Count > 0) { foreach (int id in filter.ProductGroupFilter) { groupProducts = groupProducts.Where(x => x.ProductGroupVendors.Contains(id)); } } } //filter all groupProducts = groupProducts.Where(x => x.ProductGroupVendors.Any(y => childIDList.Contains(y))); foreach (var mapping in productGroupMappings) { if (mapping.FilterByParentGroup) { if (filter.ProductGroupFilter.Count > 0) { foreach (int id in filter.ProductGroupFilter) { groupProducts = groupProducts.Where(x => x.ProductGroupVendors.Contains(id)); } } } } foreach (var product in groupProducts) { var currentRecord = contentProductGroups.Where( x => x.ConnectorID == connector.ConnectorID && x.ProductID == product.ProductID && x.ProductGroupMappingID == parent.ProductGroupMappingID).SingleOrDefault(); if (currentRecord == null) { var newRecord = new ContentProductGroup() { ConnectorID = connector.ConnectorID, ProductID = product.ProductID, ProductGroupMappingID = parent.ProductGroupMappingID, Exists = true, CreationTime = DateTime.Now, CreatedBy = Concentrator.Objects.Web.Client.User.UserID }; newContentProductGroupsToInsertInDb.Add(newRecord); contentProductGroups.Add(newRecord); } else { currentRecord.Exists = true; } } //unit.Save(); } else { foreach (var mapping in productGroupMappings) { var childMappings = pDb.Fetch <ProductGroupMapping>("SELECT * FROM ProductGroupMapping WHERE ParentProductGroupMappingID = @0", mapping.ProductGroupMappingID); bool hasChildren = childMappings.Count > 0; if (hasChildren) { var childFilter = new FilterInfo(); // do child groups if (mapping.FilterByParentGroup) { childFilter.ProductGroupFilter.AddRange(filter.ProductGroupFilter); } childFilter.ProductGroupFilter.Add(mapping.ProductGroupID); childFilter.Flatten = mapping.FlattenHierarchy; ProcessProductGroups(pDb, connector, content, childMappings, childFilter, mapping, contentProductGroups, newContentProductGroupsToInsertInDb); } else { var groupProducts = content.Where(c => c.ProductGroupVendors.Contains(mapping.ProductGroupID)).ToList(); if (mapping.FilterByParentGroup) { if (filter.ProductGroupFilter.Count > 0) { foreach (int id in filter.ProductGroupFilter) { groupProducts = groupProducts.Where(x => x.ProductGroupVendors.Contains(id)).ToList(); } } } foreach (var product in groupProducts) { var currentRecord = contentProductGroups.Where( x => x.ConnectorID == connector.ConnectorID && x.ProductID == product.ProductID && x.ProductGroupMappingID == mapping.ProductGroupMappingID).SingleOrDefault(); if (currentRecord == null) { var newRecord = new ContentProductGroup() { ConnectorID = connector.ConnectorID, ProductID = product.ProductID, ProductGroupMappingID = mapping.ProductGroupMappingID, Exists = true, CreationTime = DateTime.Now, CreatedBy = Concentrator.Objects.Web.Client.User.UserID }; newContentProductGroupsToInsertInDb.Add(newRecord); contentProductGroups.Add(newRecord); } else { currentRecord.Exists = true; } } } } } }
public override void SendResponse(System.Web.HttpResponse response) { int iErrorNumber = 0; string sFileName = ""; try { this.CheckConnector(); this.CheckRequest(); if (!this.CurrentFolder.CheckAcl(AccessControlRules.FileUpload)) { ConnectorException.Throw(Errors.Unauthorized); } HttpPostedFile oFile = HttpContext.Current.Request.Files["NewFile"]; if (oFile != null) { sFileName = System.IO.Path.GetFileName(oFile.FileName); if (Connector.CheckFileName(sFileName) && !Config.Current.CheckIsHiddenFile(sFileName)) { // Replace dots in the name with underscores (only one dot can be there... security issue). if (Config.Current.ForceSingleExtension) { sFileName = Regex.Replace(sFileName, @"\.(?![^.]*$)", "_", RegexOptions.None); } if (!Config.Current.CheckSizeAfterScaling && this.CurrentFolder.ResourceTypeInfo.MaxSize > 0 && oFile.ContentLength > this.CurrentFolder.ResourceTypeInfo.MaxSize) { ConnectorException.Throw(Errors.UploadedTooBig); } string sExtension = System.IO.Path.GetExtension(oFile.FileName); sExtension = sExtension.TrimStart('.'); if (!this.CurrentFolder.ResourceTypeInfo.CheckExtension(sExtension)) { ConnectorException.Throw(Errors.InvalidExtension); } if (Config.Current.CheckIsNonHtmlExtension(sExtension) && !this.CheckNonHtmlFile(oFile)) { ConnectorException.Throw(Errors.UploadedWrongHtmlFile); } // Map the virtual path to the local server path. string sServerDir = this.CurrentFolder.ServerPath; string sFileNameNoExt = System.IO.Path.GetFileNameWithoutExtension(sFileName); int iCounter = 0; while (true) { string sFilePath = System.IO.Path.Combine(sServerDir, sFileName); if (System.IO.File.Exists(sFilePath)) { iCounter++; sFileName = sFileNameNoExt + "(" + iCounter + ")" + System.IO.Path.GetExtension(oFile.FileName); iErrorNumber = Errors.UploadedFileRenamed; } else { oFile.SaveAs(sFilePath); if (Config.Current.SecureImageUploads && ImageTools.IsImageExtension(sExtension) && !ImageTools.ValidateImage(sFilePath)) { System.IO.File.Delete(sFilePath); ConnectorException.Throw(Errors.UploadedCorrupt); } Settings.Images imagesSettings = Config.Current.Images; if (imagesSettings.MaxHeight > 0 && imagesSettings.MaxWidth > 0) { ImageTools.ResizeImage(sFilePath, sFilePath, imagesSettings.MaxWidth, imagesSettings.MaxHeight, true, imagesSettings.Quality); if (Config.Current.CheckSizeAfterScaling && this.CurrentFolder.ResourceTypeInfo.MaxSize > 0) { long fileSize = new System.IO.FileInfo(sFilePath).Length; if (fileSize > this.CurrentFolder.ResourceTypeInfo.MaxSize) { System.IO.File.Delete(sFilePath); ConnectorException.Throw(Errors.UploadedTooBig); } } } break; } } } else { ConnectorException.Throw(Errors.InvalidName); } } else { ConnectorException.Throw(Errors.UploadedCorrupt); } } catch (ConnectorException connectorException) { iErrorNumber = connectorException.Number; } catch { iErrorNumber = Errors.Unknown; } response.Clear(); response.Write("<script type=\"text/javascript\">"); response.Write(this.GetJavaScriptCode(iErrorNumber, sFileName, this.CurrentFolder.Url + sFileName)); response.Write("</script>"); response.End(); }
internal IEnumerable <KeyValuePair <string, string> > GetDisplayName(string id) => Connector.ExecuteReader(getDisplayNameQuery, new Dictionary <string, object>() { { "Id", id } }, reader => new KeyValuePair <string, string>(reader["Language"] as string, reader["DisplayName"] as string));
public Mouse() { Brand = "Dell"; ConnectorType = Connector.USBTypeB; ButtonCount = 52; }
public GetStorebook() { InitializeComponent(); this.dataGridView1.DataSource = Connector.SelectBookTable().Tables[0].DefaultView; }
public void SaveChanges(Connector connector) { Transactional.SaveChanges(connector, new IRecordsetBase[] { this }); }
public async Task SaveChangesAsync(Connector connector) { await Transactional.SaveChangesAsync(connector, new IRecordsetBase[] { this }); }
public async Task ExecSqlAsync(Connector connector) { await Transactional.ExecSqlAsync(connector, new IRecordsetBase[] { this }); }
public void ExecSql(Connector connector) { Transactional.ExecSql(connector, new IRecordsetBase[] { this }); }
public Result Run() { Trace.Listeners.Clear(); Trace.AutoFlush = true; string outputFileName = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "AutoRoute.log"); if (File.Exists(outputFileName)) { File.Delete(outputFileName); } TextWriterTraceListener listener = new TextWriterTraceListener(outputFileName); Trace.Listeners.Add(listener); // ElementClassFilter systemTypeFilter = new ElementClassFilter(typeof(MEPSystemType)); FilteredElementCollector C = new FilteredElementCollector(m_document); C.WherePasses(systemTypeFilter); foreach (MEPSystemType type in C) { if (type.SystemClassification == MEPSystemClassification.SupplyAir) { m_systemTypeId = type.Id; //送风系统 break; } } Transaction transaction = new Transaction(m_document, "Sample_AutoRoute"); try { transaction.Start(); //标高 m_level = Level.Create(m_document, 0.0); //Element List <Autodesk.Revit.DB.ElementId> ids = new List <ElementId>(); ids.Add(new ElementId(730127)); //baseEquipment ids.Add(new ElementId(730237)); ids.Add(new ElementId(730244)); //Init Elements Info FamilyInstance[] instances = new FamilyInstance[3]; BoundingBoxXYZ[] boxes = new BoundingBoxXYZ[3]; Connector[] conns = new Connector[3]; ConnectorSetIterator csi = null; for (int i = 0; i < ids.Count; i++) { Element element = m_document.GetElement(ids[i]); if (null == element) { return(Result.Failed); } instances[i] = element as FamilyInstance; csi = ConnectorInfo.GetConnectors(element).ForwardIterator(); csi.MoveNext(); conns[i] = csi.Current as Connector; boxes[i] = instances[i].get_BoundingBox(m_document.ActiveView); } //Find the "Out" and "SupplyAir" connector on the base equipment //the first element is base equipment var baseEquipment = instances[0]; csi = ConnectorInfo.GetConnectors(baseEquipment).ForwardIterator(); while (csi.MoveNext()) { Connector conn = csi.Current as Connector; if (conn.Domain == Domain.DomainHvac || conn.Domain == Domain.DomainPiping) { //conn.Direction 只有DomainHvac和DomainPiping有 if (conn.Direction == FlowDirectionType.Out) { DuctSystemType ductSystemType = DuctSystemType.UndefinedSystemType; try { //DuctSystemType PipeSystemType ElectricalSystemType //每个连接件只有上述三个中的一个,调用其他时回报异常 ductSystemType = conn.DuctSystemType; } catch { continue; } if (ductSystemType == DuctSystemType.SupplyAir) { conns[0] = conn; break; } } } } //mechanicalSystem m_mechanicalSystem = CreateMechanicalSystem( //[378728][SupplyAir][Out][RectProfile][OST_MechanicalEquipment] new ConnectorInfo(baseEquipment, conns[0].Origin.X, conns[0].Origin.Y, conns[0].Origin.Z), new ConnectorInfo[] { //[378707][SupplyAir][In][RectProfile] new ConnectorInfo(instances[1], conns[1].Origin.X, conns[1].Origin.Y, conns[1].Origin.Z), //[378716][SupplyAir][In][RectProfile] new ConnectorInfo(instances[2], conns[2].Origin.X, conns[2].Origin.Y, conns[2].Origin.Z) }, DuctSystemType.SupplyAir ); //Get the boundary of the system double minX = conns[0].Origin.X; double minY = conns[0].Origin.Y; double maxX = conns[0].Origin.X; double maxY = conns[0].Origin.Y; double maxZ = conns[0].Origin.Z; for (int i = 1; i < boxes.Length; ++i) { if (conns[i].Origin.X < minX) { minX = conns[i].Origin.X; } if (conns[i].Origin.Y < minY) { minY = conns[i].Origin.Y; } if (conns[i].Origin.X > maxX) { maxX = conns[i].Origin.X; } if (conns[i].Origin.Y > maxY) { maxY = conns[i].Origin.Y; } if (conns[i].Origin.Z > maxZ) { maxZ = conns[i].Origin.Z; } } //Calculate the optional values(可选值) for the trunk ducts double midX = (minX + maxX) / 2; double midY = (minY + maxY) / 2; double[] baseXValues = new double[3] { midX, (minX + midX) / 2, (maxX + midX) / 2 }; double[] baseYValues = new double[3] { midY, (minY + midY) / 2, (maxY + midY) / 2 }; //ductType m_ductType = m_document.GetElement(m_ductTypeId) as DuctType; List <XYZ> points = new List <XYZ>(); //conn[0]相关点 #region conn[0] XYZ connectorDirection = conns[0].CoordinateSystem.BasisZ; if (0 == connectorDirection.DistanceTo(new XYZ(-1, 0, 0))) { points.Add(new XYZ(conns[0].Origin.X - min1FittingLength, conns[0].Origin.Y, conns[0].Origin.Z)); points.Add(new XYZ(conns[0].Origin.X - min2FittingsLength, conns[0].Origin.Y, conns[0].Origin.Z + min1FittingLength)); points.Add(new XYZ(conns[0].Origin.X - min2FittingsLength, conns[0].Origin.Y, maxZ + verticalTrunkOffset - min1FittingLength)); } else if (0 == connectorDirection.DistanceTo(new XYZ(1, 0, 0))) { points.Add(new XYZ(conns[0].Origin.X + min1FittingLength, conns[0].Origin.Y, conns[0].Origin.Z)); points.Add(new XYZ(conns[0].Origin.X + min2FittingsLength, conns[0].Origin.Y, conns[0].Origin.Z + min1FittingLength)); points.Add(new XYZ(conns[0].Origin.X + min2FittingsLength, conns[0].Origin.Y, maxZ + verticalTrunkOffset - min1FittingLength)); } else if (0 == connectorDirection.DistanceTo(new XYZ(0, -1, 0))) { points.Add(new XYZ(conns[0].Origin.X, conns[0].Origin.Y - min1FittingLength, conns[0].Origin.Z)); points.Add(new XYZ(conns[0].Origin.X, conns[0].Origin.Y - min2FittingsLength, conns[0].Origin.Z + min1FittingLength)); points.Add(new XYZ(conns[0].Origin.X, conns[0].Origin.Y - min2FittingsLength, maxZ + verticalTrunkOffset - min1FittingLength)); } else if (0 == connectorDirection.DistanceTo(new XYZ(0, 1, 0))) { points.Add(new XYZ(conns[0].Origin.X, conns[0].Origin.Y + min1FittingLength, conns[0].Origin.Z)); points.Add(new XYZ(conns[0].Origin.X, conns[0].Origin.Y + min2FittingsLength, conns[0].Origin.Z + min1FittingLength)); points.Add(new XYZ(conns[0].Origin.X, conns[0].Origin.Y + min2FittingsLength, maxZ + verticalTrunkOffset - min1FittingLength)); } #endregion //开始创建风管 List <Duct> ducts = new List <Duct>(); List <Connector> connectors = new List <Connector>(); List <Connector> baseConnectors = new List <Connector>(); ducts.Add(Duct.Create(m_document, m_ductTypeId, m_level.Id, conns[0], points[0])); ducts.Add(Duct.Create(m_document, m_systemTypeId, m_ductTypeId, m_level.Id, points[1], points[2])); connectors.Add(ConnectorInfo.GetConnector(ducts[0], points[0])); connectors.Add(ConnectorInfo.GetConnector(ducts[1], points[1])); connectors.Add(ConnectorInfo.GetConnector(ducts[1], points[2])); //连接管道,二选一,效果是一样的 //connectors[0].ConnectTo(connectors[1]); m_document.Create.NewElbowFitting(connectors[0], connectors[1]); baseConnectors.Add(connectors[2]); //Create the vertical ducts for terminals points.Clear(); ducts.Clear(); //conn[1] conn[2] 相关点 points.Add(new XYZ(conns[1].Origin.X, conns[1].Origin.Y, maxZ + verticalTrunkOffset - min1FittingLength)); points.Add(new XYZ(conns[2].Origin.X, conns[2].Origin.Y, maxZ + verticalTrunkOffset - min1FittingLength)); ducts.Add(Duct.Create(m_document, m_ductTypeId, m_level.Id, conns[1], points[0])); ducts.Add(Duct.Create(m_document, m_ductTypeId, m_level.Id, conns[2], points[1])); baseConnectors.Add(ConnectorInfo.GetConnector(ducts[0], points[0])); baseConnectors.Add(ConnectorInfo.GetConnector(ducts[1], points[1])); ////最顶部的 baseConnectors 相关 //SortConnectorsByX(baseConnectors); //for (int i = 0; i < baseYValues.Length; ++i) //{ // if (ConnectSystemOnXAxis(baseConnectors, baseYValues[i])) // { // LogUtility.WriteMechanicalSystem(m_mechanicalSystem); // return Autodesk.Revit.UI.Result.Succeeded; // } //} SortConnectorsByY(baseConnectors); for (int i = 0; i < baseXValues.Length; ++i) { if (ConnectSystemOnYAxis(baseConnectors, baseXValues[i])) { LogUtility.WriteMechanicalSystem(m_mechanicalSystem); transaction.Commit(); return(Autodesk.Revit.UI.Result.Succeeded); } } ////如果任然无法连接,把干管放到maxbbox外 //SortConnectorsByX(baseConnectors); //if (ConnectSystemOnXAxis(baseConnectors, maxY + horizontalOptionalTrunkOffset)) //{ // LogUtility.WriteMechanicalSystem(m_mechanicalSystem); // return Autodesk.Revit.UI.Result.Succeeded; //} //SortConnectorsByY(baseConnectors); //if (ConnectSystemOnYAxis(baseConnectors, maxX + horizontalOptionalTrunkOffset)) //{ // LogUtility.WriteMechanicalSystem(m_mechanicalSystem); // return Autodesk.Revit.UI.Result.Succeeded; //} ////如果任然无法连接,随便连一个,让revit报错吧 //connectors.Clear(); //SortConnectorsByX(baseConnectors); //connectors.AddRange(CreateDuct(new XYZ(baseConnectors[0].Origin.X + min1FittingLength, baseYValues[0], maxZ + verticalTrunkOffset), new XYZ(baseConnectors[1].Origin.X - min1FittingLength, baseYValues[0], maxZ + verticalTrunkOffset))); //connectors.AddRange(CreateDuct(new XYZ(baseConnectors[1].Origin.X + min1FittingLength, baseYValues[0], maxZ + verticalTrunkOffset), new XYZ(baseConnectors[2].Origin.X - min1FittingLength, baseYValues[0], maxZ + verticalTrunkOffset))); //ConnectWithElbowFittingOnXAxis(baseConnectors[0], connectors[0]); //ConnectWithElbowFittingOnXAxis(baseConnectors[2], connectors[3]); //ConnectWithTeeFittingOnXAxis(baseConnectors[1], connectors[1], connectors[2], false); } catch (Exception ex) { transaction.RollBack(); Trace.WriteLine(ex.ToString()); return(Autodesk.Revit.UI.Result.Failed); } finally { Trace.Flush(); listener.Close(); Trace.Close(); Trace.Listeners.Remove(listener); } transaction.RollBack(); return(Result.Succeeded); }
static IFCAnyHandle CreateLocalPlacementForConnector(ExporterIFC exporterIFC, Connector connector, IFCAnyHandle elementHandle, IFCFlowDirection flowDir) { try { IFCFile file = exporterIFC.GetFile(); IFCAnyHandle elementPlacement = IFCAnyHandleUtil.GetObjectPlacement(elementHandle); Transform origTrf = ExporterIFCUtils.GetUnscaledTransform(exporterIFC, elementPlacement); Transform connectorCoordinateSystem = connector.CoordinateSystem; if (flowDir == IFCFlowDirection.Sink) { // Reverse the direction of the connector. connectorCoordinateSystem.BasisX = -connectorCoordinateSystem.BasisX; connectorCoordinateSystem.BasisZ = -connectorCoordinateSystem.BasisZ; } Transform relTransform = origTrf.Inverse.Multiply(connectorCoordinateSystem); XYZ scaledOrigin = UnitUtil.ScaleLength(relTransform.Origin); IFCAnyHandle relLocalPlacement = ExporterUtil.CreateAxis2Placement3D(file, scaledOrigin, relTransform.BasisZ, relTransform.BasisX); return(IFCInstanceExporter.CreateLocalPlacement(file, elementPlacement, relLocalPlacement)); } catch { } return(null); }
public Mouse(string brand, Connector connector, int buttonCount) { Brand = brand; ConnectorType = connector; ButtonCount = buttonCount; }
public void Conditional_update_in_transaction() { int[] accountIds = null; using (var connector = new Connector(_clientConfig)) { var accounts = connector.DataSource <Account>(); accountIds = connector.GenerateUniqueIds("account_id", 2); var tIds = connector.GenerateUniqueIds("transfer_ids", 2); accounts.Put(new Account { Id = accountIds[0], Balance = 1000 }); accounts.Put(new Account { Id = accountIds[1], Balance = 0 }); // first transaction should succeed { var transferredMoney = 334; var transaction = connector.BeginTransaction(); transaction.UpdateIf(new Account { Id = accountIds[0], Balance = 1000 - transferredMoney }, account => account.Balance >= transferredMoney); transaction.Put(new Account { Id = accountIds[1], Balance = transferredMoney }); transaction.Put(new MoneyTransfer { Id = tIds[0], Amount = transferredMoney, SourceAccount = accountIds[0], DestinationAccount = accountIds[1] }); transaction.Commit(); // check that everything is updated in memory var src = accounts[accountIds[0]]; var dst = accounts[accountIds[1]]; Assert.AreEqual(666, src.Balance); Assert.AreEqual(334, dst.Balance); var transfers = connector.DataSource <MoneyTransfer>(); var transfer = transfers.Single(); Assert.AreEqual(334, transfer.Amount); Assert.AreEqual(334, transfer.Amount); } // second transaction should fail { var transferredMoney = 1001; var transaction = connector.BeginTransaction(); transaction.UpdateIf(new Account { Id = accountIds[0], Balance = 1000 - transferredMoney }, account => account.Balance >= transferredMoney); transaction.Put(new Account { Id = accountIds[1], Balance = transferredMoney }); transaction.Put(new MoneyTransfer { Id = tIds[0], Amount = transferredMoney, SourceAccount = accountIds[0], DestinationAccount = accountIds[1] }); try { transaction.Commit(); Assert.Fail("Should have thrown an exception"); } catch (CacheException e) { Assert.IsTrue(e.IsTransactionException); Assert.AreEqual(ExceptionType.ConditionNotSatisfied, e.ExceptionType); Console.WriteLine(e); } // check that nothing is updated in memory var src = accounts[accountIds[0]]; var dst = accounts[accountIds[1]]; Assert.AreEqual(666, src.Balance); Assert.AreEqual(334, dst.Balance); var transfers = connector.DataSource <MoneyTransfer>(); var transfer = transfers.Single(); Assert.AreEqual(334, transfer.Amount); Assert.AreEqual(334, transfer.Amount); } } // check that everything is persisted ok using (var connector = new Connector(_clientConfig)) { var accounts = connector.DataSource <Account>(); var src = accounts[accountIds[0]]; var dst = accounts[accountIds[1]]; Assert.AreEqual(666, src.Balance); Assert.AreEqual(334, dst.Balance); var transfers = connector.DataSource <MoneyTransfer>(); var transfer = transfers.Single(); Assert.AreEqual(334, transfer.Amount); } }
public LanguageRepository(Connector connector) : base(connector) { }
private void fresh_btn_Click(object sender, EventArgs e) { this.dataGridView1.DataSource = Connector.SelectBookTable().Tables[0].DefaultView; }
public R_FilePaste(Connector Client, byte[] packet) : base(Client, packet) { c = Client; }
public string DBState() { connector = Connector.GetInstance(); return(connector.IsConnected() ? "OK" : null); }
/// <summary> /// Creates a new pipe. /// </summary> /// <param name="doc"></param> /// <param name="parm"></param> /// <param name="startConn"></param> /// <param name="endConn"></param> /// <returns></returns> public static Pipe CreatePipe(this Document doc, PipeParameter parm, Connector startConn, Connector endConn) { if (doc is null) { throw new ArgumentNullException(nameof(doc)); } if (parm is null) { throw new ArgumentNullException(nameof(parm)); } if (startConn is null) { throw new ArgumentNullException(nameof(startConn)); } if (endConn is null) { throw new ArgumentNullException(nameof(endConn)); } return(Pipe.Create(doc, parm.TypeId, parm.LevelId, startConn, endConn)); }
public async Task ExecSqlAsync(Connector connector, int?SalesOrderID, int?SalesReasonID) { _inputparametervalues[0] = SalesOrderID; _inputparametervalues[1] = SalesReasonID; await Transactional.ExecSqlAsync(connector, new IRecordsetBase[] { this }); }
static void AddConnection(ExporterIFC exporterIFC, Connector connector, Connector connected, bool isBiDirectional, bool isElectricalDomain) { // Port connection is changed in IFC4 to use IfcRelNests for static connection. IfcRelConnectsPortToElement is used for a dynamic connection and it is restricted to IfcDistributionElement bool isIFC4AndAbove = !ExporterCacheManager.ExportOptionsCache.ExportAsOlderThanIFC4; Element inElement = connector.Owner; Element outElement = connected.Owner; if (isElectricalDomain) { // We may get a connection back to the original element. Ignore it. if (inElement.Id == outElement.Id) { return; } // Check the outElement to see if it is a Wire; if so, get its connections and "skip" the wire. if (outElement is Wire) { if (m_ProcessedWires.Contains(outElement.Id)) { return; } m_ProcessedWires.Add(outElement.Id); try { ConnectorSet wireConnectorSet = MEPCache.GetConnectorsForWire(outElement as Wire); if (wireConnectorSet != null) { foreach (Connector connectedToWire in wireConnectorSet) { ProcessConnections(exporterIFC, connectedToWire, connector); } } } catch { } return; } } // Check if the connection already exist if (ConnectionExists(inElement.Id, outElement.Id)) { return; } if (isBiDirectional) { if (ConnectionExists(outElement.Id, inElement.Id)) { return; } } IFCAnyHandle inElementIFCHandle = ExporterCacheManager.MEPCache.Find(inElement.Id); IFCAnyHandle outElementIFCHandle = ExporterCacheManager.MEPCache.Find(outElement.Id); // Note: In IFC4 the IfcRelConnectsPortToElement should be used for a dynamic connection. The static connection should use IfcRelNests if (ExporterCacheManager.ExportOptionsCache.ExportAs4) { if (inElementIFCHandle == null || outElementIFCHandle == null || !IFCAnyHandleUtil.IsSubTypeOf(inElementIFCHandle, IFCEntityType.IfcObjectDefinition) || !IFCAnyHandleUtil.IsSubTypeOf(outElementIFCHandle, IFCEntityType.IfcObjectDefinition)) { return; } } else { if (inElementIFCHandle == null || outElementIFCHandle == null || !IFCAnyHandleUtil.IsSubTypeOf(inElementIFCHandle, IFCEntityType.IfcElement) || !IFCAnyHandleUtil.IsSubTypeOf(outElementIFCHandle, IFCEntityType.IfcElement)) { return; } } IFCFile ifcFile = exporterIFC.GetFile(); IFCAnyHandle ownerHistory = ExporterCacheManager.OwnerHistoryHandle; IFCAnyHandle portOut = null; IFCAnyHandle portIn = null; // ----------------------- In Port ---------------------- { string guid = GUIDUtil.CreateGUID(); IFCFlowDirection flowDir = (isBiDirectional) ? IFCFlowDirection.SourceAndSink : IFCFlowDirection.Sink; IFCAnyHandle localPlacement = CreateLocalPlacementForConnector(exporterIFC, connector, inElementIFCHandle, flowDir); string portName = "InPort_" + inElement.Id; string portType = "Flow"; // Assigned as Port.Description portIn = IFCInstanceExporter.CreateDistributionPort(exporterIFC, null, guid, ownerHistory, localPlacement, null, flowDir); IFCAnyHandleUtil.OverrideNameAttribute(portIn, portName); IFCAnyHandleUtil.SetAttribute(portIn, "Description", portType); // Attach the port to the element guid = GUIDUtil.CreateGUID(); string connectionName = inElement.Id + "|" + guid; // Port connection is changed in IFC4 to use IfcRelNests for static connection. IfcRelConnectsPortToElement is used for a dynamic connection and it is restricted to IfcDistributionElement // The following code collects the ports that are nested to the object to be assigned later if (isIFC4AndAbove) { AddNestedMembership(inElementIFCHandle, portIn); } else { IFCInstanceExporter.CreateRelConnectsPortToElement(ifcFile, guid, ownerHistory, connectionName, portType, portIn, inElementIFCHandle); } } // ----------------------- Out Port---------------------- { string guid = GUIDUtil.CreateGUID(); IFCFlowDirection flowDir = (isBiDirectional) ? IFCFlowDirection.SourceAndSink : IFCFlowDirection.Source; IFCAnyHandle localPlacement = CreateLocalPlacementForConnector(exporterIFC, connected, outElementIFCHandle, flowDir); string portName = "OutPort_" + outElement.Id; string portType = "Flow"; // Assigned as Port.Description portOut = IFCInstanceExporter.CreateDistributionPort(exporterIFC, null, guid, ownerHistory, localPlacement, null, flowDir); IFCAnyHandleUtil.OverrideNameAttribute(portOut, portName); IFCAnyHandleUtil.SetAttribute(portOut, "Description", portType); // Attach the port to the element guid = GUIDUtil.CreateGUID(); string connectionName = outElement.Id + "|" + guid; // Port connection is changed in IFC4 to use IfcRelNests for static connection. IfcRelConnectsPortToElement is used for a dynamic connection and it is restricted to IfcDistributionElement // The following code collects the ports that are nested to the object to be assigned later if (isIFC4AndAbove) { AddNestedMembership(outElementIFCHandle, portOut); } else { IFCInstanceExporter.CreateRelConnectsPortToElement(ifcFile, guid, ownerHistory, connectionName, portType, portOut, outElementIFCHandle); } } // ----------------------- Out Port -> In Port ---------------------- if (portOut != null && portIn != null) { string guid = GUIDUtil.CreateGUID(); IFCAnyHandle realizingElement = null; string connectionName = ExporterUtil.GetGlobalId(portIn) + "|" + ExporterUtil.GetGlobalId(portOut); string connectionType = "Flow"; // Assigned as Description IFCInstanceExporter.CreateRelConnectsPorts(ifcFile, guid, ownerHistory, connectionName, connectionType, portIn, portOut, realizingElement); AddConnectionInternal(inElement.Id, outElement.Id); } // Add the handles to the connector system. HashSet <MEPSystem> systemList = new HashSet <MEPSystem>(); try { MEPSystem system = connector.MEPSystem; if (system != null) { systemList.Add(system); } } catch { } if (isElectricalDomain) { foreach (MEPSystem system in systemList) { ExporterCacheManager.SystemsCache.AddElectricalSystem(system.Id); ExporterCacheManager.SystemsCache.AddHandleToElectricalSystem(system.Id, inElementIFCHandle); ExporterCacheManager.SystemsCache.AddHandleToElectricalSystem(system.Id, outElementIFCHandle); ExporterCacheManager.SystemsCache.AddHandleToElectricalSystem(system.Id, portIn); ExporterCacheManager.SystemsCache.AddHandleToElectricalSystem(system.Id, portOut); } } else { foreach (MEPSystem system in systemList) { ExporterCacheManager.SystemsCache.AddHandleToBuiltInSystem(system, inElementIFCHandle); ExporterCacheManager.SystemsCache.AddHandleToBuiltInSystem(system, outElementIFCHandle); ExporterCacheManager.SystemsCache.AddHandleToBuiltInSystem(system, portIn); ExporterCacheManager.SystemsCache.AddHandleToBuiltInSystem(system, portOut); } } }
public static string GetAttributesAssortment(int connectorID, List <int> ProductIDs, DateTime?LastUpdate, IScope scope) { var _connectorRepo = scope.Repository <Connector>(); var _funcRepo = ((IFunctionScope)scope).Repository(); Connector con = _connectorRepo.GetSingle(x => x.ConnectorID == connectorID); if (con == null) { return(String.Empty); } try { int languageID = con.ConnectorSettings.GetValueByKey <int>("LanguageID", 2); var contentAss = (from a in scope.Repository <Content>().GetAllAsQueryable() join pg in scope.Repository <ContentProductGroup>().GetAllAsQueryable() on new { a.ProductID, a.ConnectorID } equals new { pg.ProductID, pg.ConnectorID } join pgn in scope.Repository <ProductGroupLanguage>().GetAllAsQueryable() on pg.ProductGroupMapping.ProductGroupID equals pgn.ProductGroupID where a.ConnectorID == connectorID && pgn.LanguageID == languageID select new Attributes { ManufacturerID = a.Product.VendorItemNumber, ProductID = a.ProductID, BrandID = a.Product.BrandID }); var assortment = (from a in contentAss.InRange(x => x.ProductID, 2500, ProductIDs) select a).Distinct().ToList(); List <Attributes> list = new List <Attributes>(); //IEnumerable<AttributeResult> attributes = null; //attributes = _funcRepo.GetProductAttributes(null, languageID, con.ConnectorID, LastUpdate).ToList(); var attributes = (from a in scope.Repository <ContentAttribute>().GetAll() where a.LanguageID == languageID && (a.ConnectorID == null || a.ConnectorID == con.ConnectorID) select a).ToList(); var attributeDictionary = (from a in attributes group a by a.ProductID into grouped select grouped).ToDictionary(x => x.Key, y => y); foreach (var product in assortment) { var p = product; IGrouping <int?, ContentAttribute> productAttributes = null; attributeDictionary.TryGetValue(p.ProductID, out productAttributes); if (productAttributes != null) { p.AttributeList = productAttributes.ToList(); } list.Add(p); } var attributeGroups = (from att in list.SelectMany(x => x.AttributeList) select new ImportAttributeGroup { AttributeGroupID = att.GroupID, AttributeGroupIndex = att.GroupIndex, AttributeGroupName = att.GroupName }).Distinct().ToList(); using (var stringWriter = new StringWriterWithEncoding(Encoding.UTF8)) { using (var writer = new XmlTextWriter(stringWriter) { Formatting = Formatting.None }) { writer.WriteStartDocument(true); writer.WriteStartElement("ProductAttributes"); foreach (var a in list.Where(x => x.AttributeList.Count > 0)) { var groupIds = a.AttributeList.Select(x => x.GroupID).Distinct().ToList(); var productAttributeGroups = attributeGroups.Where(x => groupIds.Contains(x.AttributeGroupID)); #region Element var element = new XElement("ProductAttribute", new XAttribute("ProductID", a.ProductID), new XAttribute("ManufacturerID", a.ManufacturerID), new XElement("Brand", new XAttribute("BrandID", a.BrandID)), new XElement("AttributeGroups", (from pag in productAttributeGroups select new XElement("AttributeGroup", new XAttribute( "AttributeGroupID", pag.AttributeGroupID), new XAttribute( "AttributeGroupIndex", pag. AttributeGroupIndex), new XAttribute("Name", pag. AttributeGroupName)) )), new XElement("Attributes", (from p in a.AttributeList //where !string.IsNullOrEmpty(p.AttributeValue) select new XElement("Attribute", new XAttribute("AttributeID", p.AttributeID), new XAttribute("AttributeCode", !string.IsNullOrEmpty( p.AttributeCode) ? p.AttributeCode : string.Empty), new XAttribute("KeyFeature", p.IsVisible), new XAttribute("Index", p.OrderIndex), new XAttribute("IsSearchable", p.IsSearchable), new XAttribute("AttributeGroupID", p.GroupID), new XAttribute("NeedsUpdate", p.NeedsUpdate), new XElement("Name", HttpUtility.HtmlEncode( p.AttributeName)), new XElement("Value", !string.IsNullOrEmpty( p.AttributeValue) ? p.AttributeValue : string.Empty), new XElement("Sign", HttpUtility.HtmlEncode( !string.IsNullOrEmpty( p.Sign) ? p.Sign : string.Empty)) )).Distinct()) ); element.WriteTo(writer); writer.Flush(); #endregion } writer.WriteEndElement(); // ProductAttributes writer.WriteEndDocument(); writer.Flush(); } stringWriter.Flush(); return(stringWriter.ToString()); } } catch (Exception ex) { throw ex; } }
public void ExecSql(Connector connector, int?SalesOrderID, int?SalesReasonID) { _inputparametervalues[0] = SalesOrderID; _inputparametervalues[1] = SalesReasonID; Transactional.ExecSql(connector, new IRecordsetBase[] { this }); }
public R_RemoteDesktopStart(Connector Client, byte[] packet) : base(Client, packet) { this.c = Client; }
public BUS_HoaDon() { connector = new Connector(); }
public void No_deadlock_if_transactions_and_non_transactional_queries_are_run_in_parallel() { using (var connector = new Connector(_clientConfig)) { var accounts = connector.DataSource <Account>(); var accountIds = connector.GenerateUniqueIds("account_id", 2); accounts.Put(new Account { Id = accountIds[0], Balance = 1000 }); accounts.Put(new Account { Id = accountIds[1], Balance = 0 }); // run in parallel a sequence of transactions and clients that check that the sum of the balances of the two accounts is // always the same (thus proving that the two accounts are updated transactionally) try { Parallel.Invoke( () => { Parallel.For(0, 100, i => { // check the some of two balances is always 1000 var myAccounts = accounts.ToList(); Assert.AreEqual(2, myAccounts.Count); Console.WriteLine($"balance1={myAccounts[0].Balance} balance2={myAccounts[1].Balance}"); }); }, () => { var myAccounts = accounts.ToList(); for (var i = 0; i < 80; i++) { var transfer = new MoneyTransfer { Amount = 10, Date = DateTime.Today, SourceAccount = myAccounts[0].Id, DestinationAccount = myAccounts[1].Id }; myAccounts[0].Balance -= 10; myAccounts[1].Balance += 10; var transaction = connector.BeginTransaction(); transaction.Put(myAccounts[0]); transaction.Put(myAccounts[1]); transaction.Put(transfer); transaction.Commit(); } }); } catch (Exception e) { Console.WriteLine(e.Message); Assert.Fail(e.Message); } } // check that the data is persistent (force the external server to reload data) StopServers(); StartServers(); using (var connector = new Connector(_clientConfig)) { var accounts = connector.DataSource <Account>(); var myAccounts = accounts.ToList(); Assert.AreEqual(2, myAccounts.Count); var sum = myAccounts.Sum(acc => acc.Balance); Assert.AreEqual(1000, sum); Assert.IsTrue(myAccounts.All(acc => acc.Balance < 1000), "The balance is unchanged when reloading data"); Console.WriteLine($"balance1={myAccounts[0].Balance} balance2={myAccounts[1].Balance}"); } }
public void No_deadlock_if_same_objects_are_updated_in_parallel_by_multiple_clients() { List <Account> myAccounts; using (var connector = new Connector(_clientConfig)) { var accounts = connector.DataSource <Account>(); var accountIds = connector.GenerateUniqueIds("account_id", 2); accounts.Put(new Account { Id = accountIds[0], Balance = 1000 }); accounts.Put(new Account { Id = accountIds[1], Balance = 0 }); myAccounts = accounts.ToList(); } Parallel.Invoke( () => { using var connector1 = new Connector(_clientConfig); for (var i = 0; i < 100; i++) { var transfer = new MoneyTransfer { Amount = 10, Date = DateTime.Today, SourceAccount = myAccounts[0].Id, DestinationAccount = myAccounts[1].Id }; myAccounts[0].Balance -= 10; myAccounts[1].Balance += 10; var transaction = connector1.BeginTransaction(); transaction.Put(myAccounts[0]); transaction.Put(myAccounts[1]); transaction.Put(transfer); transaction.Commit(); } }, () => { using var connector2 = new Connector(_clientConfig); for (var i = 0; i < 100; i++) { var transfer = new MoneyTransfer { Amount = 10, Date = DateTime.Today, SourceAccount = myAccounts[0].Id, DestinationAccount = myAccounts[1].Id }; myAccounts[0].Balance -= 10; myAccounts[1].Balance += 10; var transaction = connector2.BeginTransaction(); transaction.Put(myAccounts[0]); transaction.Put(myAccounts[1]); transaction.Put(transfer); transaction.Commit(); } }, () => { using var connector3 = new Connector(_clientConfig); for (var i = 0; i < 100; i++) { var transfer = new MoneyTransfer { Amount = 10, Date = DateTime.Today, SourceAccount = myAccounts[0].Id, DestinationAccount = myAccounts[1].Id }; myAccounts[0].Balance -= 10; myAccounts[1].Balance += 10; var transaction = connector3.BeginTransaction(); transaction.Put(myAccounts[0]); transaction.Put(myAccounts[1]); transaction.Put(transfer); transaction.Commit(); } }); TransactionStatistics.Display(); using (var connector = new Connector(_clientConfig)) { var accounts = connector.DataSource <Account>(); myAccounts = accounts.ToList(); Console.WriteLine($"balance1={myAccounts[0].Balance} balance2={myAccounts[1].Balance}"); } }
// If originalConnector != null, use that connector for AddConnection routine, instead of connector. private static void ProcessConnections(ExporterIFC exporterIFC, Connector connector, Connector originalConnector) { // Port connection is not allowed for IFC4RV MVD bool isIFC4AndAbove = !ExporterCacheManager.ExportOptionsCache.ExportAsOlderThanIFC4; Domain domain = connector.Domain; bool isElectricalDomain = (domain == Domain.DomainElectrical); bool supportsDirection = (domain == Domain.DomainHvac || domain == Domain.DomainPiping); ConnectorType connectorType = connector.ConnectorType; if (connectorType == ConnectorType.End || connectorType == ConnectorType.Curve || connectorType == ConnectorType.Physical) { Connector originalConnectorToUse = (originalConnector != null) ? originalConnector : connector; FlowDirectionType flowDirection = supportsDirection ? connector.Direction : FlowDirectionType.Bidirectional; bool isBiDirectional = (flowDirection == FlowDirectionType.Bidirectional); if (connector.IsConnected) { ConnectorSet connectorSet = connector.AllRefs; ConnectorSetIterator csi = connectorSet.ForwardIterator(); while (csi.MoveNext()) { Connector connected = csi.Current as Connector; if (connected != null && connected.Owner != null && connector.Owner != null) { if (connected.Owner.Id != connector.Owner.Id) { // look for physical connections ConnectorType connectedType = connected.ConnectorType; if (connectedType == ConnectorType.End || connectedType == ConnectorType.Curve || connectedType == ConnectorType.Physical) { if (flowDirection == FlowDirectionType.Out) { AddConnection(exporterIFC, connected, originalConnectorToUse, false, isElectricalDomain); } else { AddConnection(exporterIFC, originalConnectorToUse, connected, isBiDirectional, isElectricalDomain); } } } } } } else { string guid = GUIDUtil.CreateGUID(); IFCFlowDirection flowDir = (isBiDirectional) ? IFCFlowDirection.SourceAndSink : (flowDirection == FlowDirectionType.Out ? IFCFlowDirection.Sink : IFCFlowDirection.Source); Element hostElement = connector.Owner; IFCAnyHandle hostElementIFCHandle = ExporterCacheManager.MEPCache.Find(hostElement.Id); //if (ExporterCacheManager.ExportOptionsCache.ExportAs4 && !(IFCAnyHandleUtil.IsSubTypeOf(hostElementIFCHandle, IFCEntityType.IfcDistributionElement))) // return; IFCAnyHandle localPlacement = CreateLocalPlacementForConnector(exporterIFC, connector, hostElementIFCHandle, flowDir); IFCFile ifcFile = exporterIFC.GetFile(); IFCAnyHandle ownerHistory = ExporterCacheManager.OwnerHistoryHandle; IFCAnyHandle port = IFCInstanceExporter.CreateDistributionPort(exporterIFC, null, guid, ownerHistory, localPlacement, null, flowDir); string portName = "Port_" + hostElement.Id; IFCAnyHandleUtil.OverrideNameAttribute(port, portName); string portType = "Flow"; // Assigned as Port.Description IFCAnyHandleUtil.SetAttribute(port, "Description", portType); // Attach the port to the element guid = GUIDUtil.CreateGUID(); string connectionName = hostElement.Id + "|" + guid; IFCAnyHandle connectorHandle = null; // Port connection is changed in IFC4 to use IfcRelNests for static connection. IfcRelConnectsPortToElement is used for a dynamic connection and it is restricted to IfcDistributionElement // The following code collects the ports that are nested to the object to be assigned later if (isIFC4AndAbove) { AddNestedMembership(hostElementIFCHandle, port); } else { connectorHandle = IFCInstanceExporter.CreateRelConnectsPortToElement(ifcFile, guid, ownerHistory, connectionName, portType, port, hostElementIFCHandle); } HashSet <MEPSystem> systemList = new HashSet <MEPSystem>(); try { MEPSystem system = connector.MEPSystem; if (system != null) { systemList.Add(system); } } catch { } if (isElectricalDomain) { foreach (MEPSystem system in systemList) { ExporterCacheManager.SystemsCache.AddElectricalSystem(system.Id); ExporterCacheManager.SystemsCache.AddHandleToElectricalSystem(system.Id, hostElementIFCHandle); ExporterCacheManager.SystemsCache.AddHandleToElectricalSystem(system.Id, port); } } else { foreach (MEPSystem system in systemList) { ExporterCacheManager.SystemsCache.AddHandleToBuiltInSystem(system, hostElementIFCHandle); ExporterCacheManager.SystemsCache.AddHandleToBuiltInSystem(system, port); } } } } }
public DrawingTool() { InitializeComponent(); if (Device.RuntimePlatform == Device.Android) { Xamarin.Forms.DependencyService.Get <IText>().GenerateFactor(); } diagram.IsReadOnly = true; Node n1 = DrawNode(145, 110, 100, 55, ShapeType.Rectangle, "Node1"); if (Device.RuntimePlatform == Device.UWP) { n1.ShapeType = ShapeType.Rectangle; } n1.Style.Brush = new SolidBrush(Color.FromRgb(49, 162, 255)); n1.Style.StrokeBrush = new SolidBrush(Color.FromRgb(23, 132, 206)); PortCollection node1ports = new PortCollection(); Port port1 = new Port() { Width = 10, Height = 10, NodeOffsetX = 0.5, NodeOffsetY = 0, ShapeType = ShapeType.Circle, IsVisible = true }; Port port2 = new Port() { Width = 10, Height = 10, NodeOffsetX = 0, NodeOffsetY = 0.5, ShapeType = ShapeType.Circle, IsVisible = true }; Port port3 = new Port() { Width = 10, Height = 10, NodeOffsetX = 1, NodeOffsetY = 0.5, ShapeType = ShapeType.Circle, IsVisible = true }; Port port4 = new Port() { Width = 10, Height = 10, NodeOffsetX = 0.5, NodeOffsetY = 1, ShapeType = ShapeType.Circle, IsVisible = true }; node1ports.Add(port1); node1ports.Add(port2); node1ports.Add(port3); node1ports.Add(port4); n1.Ports = node1ports; Node n2 = DrawNode(30, 260, 100, 55, ShapeType.Rectangle, "Node2"); if (Device.RuntimePlatform == Device.UWP) { n2.ShapeType = ShapeType.Rectangle; } n2.Style.Brush = new SolidBrush(Color.FromRgb(239, 75, 93)); n2.Style.StrokeBrush = new SolidBrush(Color.FromRgb(201, 32, 61)); PortCollection node2ports = new PortCollection(); Port port5 = new Port() { Width = 10, Height = 10, NodeOffsetX = 0.5, NodeOffsetY = 0, ShapeType = ShapeType.Circle, IsVisible = true }; Port port6 = new Port() { Width = 10, Height = 10, NodeOffsetX = 0, NodeOffsetY = 0.5, ShapeType = ShapeType.Circle, IsVisible = true }; Port port7 = new Port() { Width = 10, Height = 10, NodeOffsetX = 1, NodeOffsetY = 0.5, ShapeType = ShapeType.Circle, IsVisible = true }; Port port8 = new Port() { Width = 10, Height = 10, NodeOffsetX = 0.5, NodeOffsetY = 1, ShapeType = ShapeType.Circle, IsVisible = true }; node2ports.Add(port5); node2ports.Add(port6); node2ports.Add(port7); node2ports.Add(port8); n2.Ports = node2ports; Node n3 = DrawNode(260, 260, 100, 55, ShapeType.Rectangle, "Node3"); if (Device.RuntimePlatform == Device.UWP) { n3.ShapeType = ShapeType.Rectangle; } n3.Style.Brush = new SolidBrush(Color.FromRgb(0, 194, 192)); n3.Style.StrokeBrush = new SolidBrush(Color.FromRgb(14, 142, 135)); PortCollection node3ports = new PortCollection(); Port port9 = new Port() { Width = 10, Height = 10, NodeOffsetX = 0.5, NodeOffsetY = 0, ShapeType = ShapeType.Circle, IsVisible = true }; Port port10 = new Port() { Width = 10, Height = 10, NodeOffsetX = 0, NodeOffsetY = 0.5, ShapeType = ShapeType.Circle, IsVisible = true }; Port port11 = new Port() { Width = 10, Height = 10, NodeOffsetX = 1, NodeOffsetY = 0.5, ShapeType = ShapeType.Circle, IsVisible = true }; Port port12 = new Port() { Width = 10, Height = 10, NodeOffsetX = 0.5, NodeOffsetY = 1, ShapeType = ShapeType.Circle, IsVisible = true }; node3ports.Add(port9); node3ports.Add(port10); node3ports.Add(port11); node3ports.Add(port12); n3.Ports = node3ports; Connector con1 = new Connector() { SourcePort = port4, TargetPort = port5, SegmentType = SegmentType.StraightSegment, TargetDecoratorType = DecoratorType.None }; Connector con2 = new Connector() { SourcePort = port4, TargetPort = port9, SegmentType = SegmentType.StraightSegment, TargetDecoratorType = DecoratorType.None }; Connector con3 = new Connector() { SourcePort = port7, TargetPort = port10, SegmentType = SegmentType.StraightSegment, TargetDecoratorType = DecoratorType.None }; diagram.AddNode(n1); diagram.AddNode(n2); diagram.AddNode(n3); diagram.AddConnector(con1); diagram.AddConnector(con2); diagram.AddConnector(con3); }