public MultiConnections() { UpdateBase = new FmdcEventHandler(PassiveConnectToUser_UpdateBase); // Creates a empty share Share share = new Share("Testing"); // Port to listen for incomming connections on share.Port = 12345; incomingConnectionListener = new TcpConnectionListener(share.Port); incomingConnectionListener.Update += new FmdcEventHandler(Connection_Update); incomingConnectionListener.Start(); // Adds common filelist to share AddFilelistsToShare(share); HubSetting setting = new HubSetting(); setting.Address = "127.0.0.1"; setting.Port = 411; setting.DisplayName = "FlowLib"; setting.Protocol = "Auto"; hub = new Hub(setting, this); hub.ProtocolChange += new FmdcEventHandler(hubConnection_ProtocolChange); // Adds share to hub hub.Share = share; hub.Me.Mode = FlowLib.Enums.ConnectionTypes.Direct; hub.Connect(); last = System.DateTime.Now.Ticks; timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed); timer.AutoReset = true; timer.Interval = 1000; timer.Start(); }
public FilelistMyList(Share share) : base(share) { systemPath = ""; if (share != null) fileName = share.Name; }
/// <summary> /// Adds/Update common filelists to this share and saves them in directory specified /// Filelist included are: /// BZList, XmlBzList (UTF-8 and ASCII) /// </summary> /// <param name="share">Share you want to update/add filelist to</param> /// <param name="directory">Directory where you want to save filelists in</param> public static void AddCommonFilelistsToShare(Share share, string directory) { // Xml Utf-8 (Current DC++) FlowLib.Utils.FileLists.FilelistXmlBz2 xml = new FlowLib.Utils.FileLists.FilelistXmlBz2(share); xml.SystemPath = directory; xml.Encoding = System.Text.Encoding.UTF8; xml.CreateFilelist(); share.RemoveFile(xml.ContentInfo); share.AddFile(xml.ContentInfo); // Xml Ascii (Early DC++) xml.Encoding = System.Text.Encoding.ASCII; xml.CreateFilelist(); share.RemoveFile(xml.ContentInfo); share.AddFile(xml.ContentInfo); // Xml Utf-8 (Adc Standard list) xml.Bz2 = false; xml.SystemPath = directory; xml.Encoding = System.Text.Encoding.UTF8; xml.CreateFilelist(); share.RemoveFile(xml.ContentInfo); share.AddFile(xml.ContentInfo); // BzList FlowLib.Utils.FileLists.FilelistMyList dclst = new FlowLib.Utils.FileLists.FilelistMyList(share); dclst.SystemPath = directory; dclst.CreateFilelist(); share.RemoveFile(dclst.ContentInfo); share.AddFile(dclst.ContentInfo); }
public ShareDto(Share s) { MarketCode = s.MarketCode; InstrumentCode = s.InstrumentCode; CompanyName = s.CompanyName; Prices = s.Days.Select(d => Point.With(d.Date, d.Close)).ToArray(); }
public static void Main(String[] args) { try { Curl.GlobalInit((int)CURLinitFlag.CURL_GLOBAL_ALL); dnsLock = new Object(); cookieLock = new Object(); Share share = new Share(); Share.LockFunction lf = new Share.LockFunction(OnLock); Share.UnlockFunction ulf = new Share.UnlockFunction(OnUnlock); share.SetOpt(CURLSHoption.CURLSHOPT_LOCKFUNC, lf); share.SetOpt(CURLSHoption.CURLSHOPT_UNLOCKFUNC, ulf); share.SetOpt(CURLSHoption.CURLSHOPT_SHARE, CURLlockData.CURL_LOCK_DATA_COOKIE); share.SetOpt(CURLSHoption.CURLSHOPT_SHARE, CURLlockData.CURL_LOCK_DATA_DNS); EasyThread et1 = new EasyThread(args[0], share); EasyThread et2 = new EasyThread(args[1], share); Thread t1 = new Thread(new ThreadStart(et1.ThreadFunc)); Thread t2 = new Thread(new ThreadStart(et2.ThreadFunc)); t1.Start(); t2.Start(); t1.Join(); t2.Join(); share.Cleanup(); Curl.GlobalCleanup(); } catch(Exception ex) { Console.WriteLine(ex); } }
public static string shareListString(Share[] shareList) { string shareListString = ""; for (int i = 0; i < shareList.Length - 1; i++) { shareListString += shareList[i].Name + ", "; } shareListString += shareList[shareList.Length - 1].Name; return shareListString; }
public virtual void Create( long id ) { User creator = (User)ctx.viewer.obj; String dataType = ctx.Post( "dataType" ); String name = ctx.Post( "name" ); String dataLink = ctx.Post( "dataLink" ); Type et = Entity.GetType( dataType ); IShareData targetData = ndb.findById( et, id ) as IShareData; IShareInfo shareInfo = targetData.GetShareInfo(); Share share = new Share(); share.Creator = creator; share.DataType = typeof( Share ).FullName; share.TitleTemplate = shareInfo.GetShareTitleTemplate(); share.TitleData = shareInfo.GetShareTitleData(); share.BodyTemplate = shareInfo.GetShareBodyTemplate(); share.BodyData = shareInfo.GetShareBodyData( dataLink ); share.BodyGeneral = ctx.Post( "Comment" ); Result result = shareService.Create( share ); if (result.HasErrors) { echoToParent( result.ErrorsHtml ); } else { feedService.publishUserAction( share ); shareInfo.addNotification( creator.Name, toUser( creator ) ); echoToParent( lang( "opok" ) ); } }
public Share ParseFile(string filePath) { using (var csv = new StreamReader(filePath)) { var share = new Share(); var row = 0; var days = new List<ShareDay>(); while (!csv.EndOfStream) { var cells = csv.ReadLine().Split(','); Debug.Assert(cells.Length == 9); var day = new ShareDay(); day.Date = DateTime.ParseExact(cells[2], "yyyyMMdd", CultureInfo.CurrentCulture); day.Open = Decimal.Parse(cells[3]); day.High = Decimal.Parse(cells[4]); day.Low = Decimal.Parse(cells[5]); day.Close = Decimal.Parse(cells[6]); day.Volume = UInt32.Parse(cells[7]); day.OpenInt = UInt16.Parse(cells[8]); days.Add(day); row++; } share.Days = days.ToArray(); return share; } }
public CollectTransferedInformationFromFilelistDownload() { UpdateBase = new FmdcEventHandler(PassiveConnectToUser_UpdateBase); // Creates a empty share Share share = new Share("Testing"); // Port to listen for incomming connections on share.Port = 12345; incomingConnectionListener = new TcpConnectionListener(share.Port); incomingConnectionListener.Update += new FmdcEventHandler(Connection_Update); incomingConnectionListener.Start(); // Adds common filelist to share AddFilelistsToShare(share); HubSetting setting = new HubSetting(); setting.Address = "127.0.0.1"; setting.Port = 411; setting.DisplayName = "FlowLib"; setting.Protocol = "Auto"; Hub hubConnection = new Hub(setting, this); hubConnection.ProtocolChange += new FmdcEventHandler(hubConnection_ProtocolChange); // Adds share to hub hubConnection.Share = share; //hubConnection.Me.Mode = FlowLib.Enums.ConnectionTypes.Direct; hubConnection.Me.TagInfo.Slots = 2; hubConnection.Connect(); FlowLib.Utils.Convert.General.BinaryPrefixes bp; Console.WriteLine("Press any key to update information"); do { Console.ReadKey(true); Console.Clear(); Console.WriteLine("Press any key to update information"); Console.WriteLine("=================================="); if (stats != null) { Console.WriteLine("Total data sent: " + FlowLib.Utils.Convert.General.FormatBytes(stats.TotalBytesSent, out bp) + bp); Console.WriteLine("Total data received: " + FlowLib.Utils.Convert.General.FormatBytes(stats.TotalBytesReceived, out bp) + bp); Console.WriteLine("current download speed: " + FlowLib.Utils.Convert.General.FormatBytes(stats.CurrentReceiveSpeed, out bp) + bp + "/s"); Console.WriteLine("current upload speed: " + FlowLib.Utils.Convert.General.FormatBytes(stats.CurrentSendSpeed, out bp) + bp + "/s"); Decimal d = new decimal(stats.MaximumReceiveSpeed); Console.WriteLine("Maximum download speed: " + FlowLib.Utils.Convert.General.FormatBytes(decimal.ToInt64(d), out bp) + bp + "/s"); d = new decimal(stats.MaximumSendSpeed); Console.WriteLine("Maximum upload speed: " + FlowLib.Utils.Convert.General.FormatBytes(decimal.ToInt64(d), out bp) + bp + "/s"); d = new decimal(stats.MinimumReceiveSpeed); Console.WriteLine("Minimum download speed: " + FlowLib.Utils.Convert.General.FormatBytes(decimal.ToInt64(d), out bp) + bp + "/s"); d = new decimal(stats.MinimumSendSpeed); Console.WriteLine("Minimum upload speed: " + FlowLib.Utils.Convert.General.FormatBytes(decimal.ToInt64(d), out bp) + bp + "/s"); } else { Console.WriteLine("No transfer has started yet."); } Console.WriteLine("=================================="); } while (true); }
public JsonResult ShareArticle(Guid id, string email) { if (ModelState.IsValid) { User user = db.Users.Where(x => x.Email == email).FirstOrDefault(); if (user == null) { string variableName = "Email does not exist"; return Json(variableName, JsonRequestBehavior.AllowGet); } Article article = db.Articles.Where(x => x.ArticleID == id).FirstOrDefault(); if (article.UserID == user.UserID) { string variableName1 = "You cannot share with yourself"; return Json(variableName1, JsonRequestBehavior.AllowGet); } Share share1 = db.Shares.Where(x => x.ArticleID == id && x.UserID == user.UserID).FirstOrDefault(); if (share1 != null) { string variableName1 = "The article is already shared with the user"; return Json(variableName1, JsonRequestBehavior.AllowGet); } Share share = new Share(); share.ShareID = Guid.NewGuid(); share.ArticleID = id; share.UserID = user.UserID; db.Shares.Add(share); db.SaveChanges(); } return Json(null, JsonRequestBehavior.AllowGet); }
public ActiveEmptySharingUsingTLS() { // Creates a empty share Share share = new Share("Testing"); // Port to listen for incomming connections on share.Port = 12345; AddFilelistsToShare(share); incomingConnectionListener = new TcpConnectionListener(share.Port); incomingConnectionListener.Update += new FmdcEventHandler(Connection_Update); incomingConnectionListener.Start(); // TLS listener incomingConnectionListenerTLS = new TcpConnectionListener(tlsport); incomingConnectionListenerTLS.Update += new FmdcEventHandler(Connection_UpdateTLS); incomingConnectionListenerTLS.Start(); HubSetting setting = new HubSetting(); setting.Address = "127.0.0.1"; setting.Port = 411; setting.DisplayName = "FlowLibActiveTLS"; setting.Protocol = "Auto"; Hub hubConnection = new Hub(setting); hubConnection.ProtocolChange += new FmdcEventHandler(hubConnection_ProtocolChange); hubConnection.Share = share; hubConnection.Me.Mode = FlowLib.Enums.ConnectionTypes.Direct; #if !COMPACT_FRAMEWORK // Security, Windows Mobile doesnt support SSLStream so we disable this feature for it. hubConnection.Me.Set(UserInfo.SECURE, tlsport.ToString()); #endif hubConnection.Connect(); }
public ActiveSearch() { UpdateBase = new FmdcEventHandler(ActiveSearch_UpdateBase); HubSetting settings = new HubSetting(); settings.Address = "127.0.0.1"; settings.Port = 411; settings.DisplayName = "FlowLib"; settings.Protocol = "Auto"; hubConnection = new Hub(settings, this); hubConnection.ProtocolChange += new FmdcEventHandler(hubConnection_ProtocolChange); hubConnection.Connect(); Share share = new Share("Test"); share.Port = 1000; // Telling that we are listening on port 1000 for incomming search results (Any means from everyone) UdpConnection udp = new UdpConnection(new IPEndPoint(IPAddress.Any, share.Port)); udp.Protocol = new FlowLib.Protocols.UdpNmdcProtocol(); udp.Protocol.MessageReceived += new FmdcEventHandler(Protocol_MessageReceived); // Enable Active searching hubConnection.Me.Mode = FlowLib.Enums.ConnectionTypes.Direct; hubConnection.Share = share; }
public ActiveDownloadFilelistFromUser() { UpdateBase = new FmdcEventHandler(PassiveConnectToUser_UpdateBase); // Creates a empty share Share share = new Share("Testing"); // Port to listen for incomming connections on share.Port = 12345; incomingConnectionListener = new TcpConnectionListener(share.Port); incomingConnectionListener.Update += new FmdcEventHandler(Connection_Update); incomingConnectionListener.Start(); // Adds common filelist to share AddFilelistsToShare(share); HubSetting setting = new HubSetting(); setting.Address = "127.0.0.1"; setting.Port = 411; setting.DisplayName = "FlowLib"; setting.Protocol = "Auto"; Hub hubConnection = new Hub(setting, this); hubConnection.ProtocolChange += new FmdcEventHandler(hubConnection_ProtocolChange); // Adds share to hub hubConnection.Share = share; hubConnection.Me.Mode = FlowLib.Enums.ConnectionTypes.Direct; hubConnection.Connect(); }
public DcBot(HubSetting settings) { UpdateBase = new FlowLib.Events.FmdcEventHandler(DcBot_UpdateBase); downloadManager.DownloadCompleted += new FmdcEventHandler(downloadManager_DownloadCompleted); // Creates a empty share Share share = new Share("Testing"); // Do we want bot to be active? if (Program.USE_ACTIVE_MODE) { if (Program.PORT_TLS > 0) { share.Port = Program.PORT_TLS; } else { share.Port = Program.PORT_ACTIVE; } incomingConnectionListener = new TcpConnectionListener(Program.PORT_ACTIVE); incomingConnectionListener.Update += new FmdcEventHandler(Connection_Update); incomingConnectionListener.Start(); // TLS listener incomingConnectionListenerTLS = new TcpConnectionListener(Program.PORT_TLS); incomingConnectionListenerTLS.Update += new FmdcEventHandler(Connection_UpdateTLS); incomingConnectionListenerTLS.Start(); } // Adds common filelist to share AddFilelistsToShare(share); hubConnection = new Hub(settings, this); hubConnection.Me.TagInfo.Version = "Serie V:20101125"; hubConnection.Me.TagInfo.Slots = 2; // DO NOT CHANGE THIS LINE! hubConnection.Me.Set(UserInfo.PID, "7OP7K374IKV7YMEYUI5F5R4YICFT36M7FL64AWY"); // Adds share to hub hubConnection.Share = share; // Do we want bot to be active? if (Program.USE_ACTIVE_MODE) { hubConnection.Me.TagInfo.Mode = FlowLib.Enums.ConnectionTypes.Direct; hubConnection.Me.Set(UserInfo.SECURE, Program.PORT_TLS.ToString()); } else { hubConnection.Me.TagInfo.Mode = FlowLib.Enums.ConnectionTypes.Passive; hubConnection.Me.Set(UserInfo.SECURE, ""); } hubConnection.ConnectionStatusChange += new FmdcEventHandler(hubConnection_ConnectionStatusChange); hubConnection.ProtocolChange += new FmdcEventHandler(hubConnection_ProtocolChange); hubConnection.SecureUpdate += new FmdcEventHandler(hubConnection_SecureUpdate); }
/// <summary> /// Adding share to manager /// </summary> /// <param name="s">Share we want to add</param> /// <returns>Returns true if share name is not already existing (and is added)</returns> public bool AddShare(Share s) { if (!s.Name.Contains("|") && !shares.ContainsKey(s.Name)) { shares.Add(s.Name, s); Save(); return true; } return false; }
public void TrackerExposesInstantiatedShareAsAProperty() { Share sasol = new Share() { ShortCode = "SOL" }; using (ShareTracker tracker = new ShareTracker(sasol)) { Assert.True(tracker.Share == sasol); } }
public void NewTrackerStartsPollForNewPrices() { Share sasol = new Share() { ShortCode = "SOL", LastTradePrice = -1 }; using (ShareTracker tracker = new ShareTracker(sasol, 1)) { System.Threading.Thread.Sleep(25); Assert.NotEqual(-1, tracker.Share.LastTradePrice); } }
public PassiveEmptySharing() { // Creates a empty share Share share = new Share("Testing"); // Adds common filelist to share AddFilelistsToShare(share); HubSetting setting = new HubSetting(); setting.Address = "127.0.0.1"; setting.Port = 411; setting.DisplayName = "FlowLib"; setting.Protocol = "Auto"; Hub hubConnection = new Hub(setting); hubConnection.ProtocolChange += new FmdcEventHandler(hubConnection_ProtocolChange); // Adds share to hub hubConnection.Share = share; hubConnection.Connect(); }
public ShareTracker(Share share, int updateInterval) { if (share == null) { throw new ArgumentNullException("share"); } _share = share; Clients = new ConcurrentBag<string>(); _timer = new Timer(updateInterval); _timer.Elapsed += (s, e) => { CheckForShareUpdates(); }; _timer.Start(); }
public virtual Result CreateUrl( User user, String shareLink, String shareDescription ) { Share share = new Share(); share.Creator = user; share.DataType = typeof( Share ).FullName; String titleTemplate = string.Format( lang.get( "shareInfo" ), "{*actor*}" ); //String titleTemplate = "{*actor*} 分享了一个网址"; String titleData = ""; share.TitleTemplate = titleTemplate; share.TitleData = titleData; String bodyTemplate = @"<div><a href=""{*postLink*}"">{*postLink*}</a></div><div class=""note"">{*body*}</div>"; String bodyData = "{postLink:\"" + shareLink + "\", body:\"" + shareDescription + "\"}"; share.BodyTemplate = bodyTemplate; share.BodyData = bodyData; return share.insert(); }
public PassiveDownloadFilelistFromUserUsingTLS() { UpdateBase = new FmdcEventHandler(PassiveConnectToUser_UpdateBase); // Creates a empty share Share share = new Share("Testing"); // Adds common filelist to share AddFilelistsToShare(share); HubSetting setting = new HubSetting(); setting.Address = "127.0.0.1"; setting.Port = 411; setting.DisplayName = "FlowLibPassiveTLS"; setting.Protocol = "Auto"; Hub hubConnection = new Hub(setting, this); hubConnection.ProtocolChange += new FmdcEventHandler(hubConnection_ProtocolChange); // Adds share to hub hubConnection.Share = share; hubConnection.Me.Set(UserInfo.SECURE, ""); hubConnection.Connect(); }
public void TrackerExposesPriceUpdatedEventWhichNotifiesOfUpdatedPrices() { Share sasol = new Share { ShortCode = "SOL", LastTradePrice = -1 }; using (ShareTracker tracker = new ShareTracker(sasol, 1)) { var eventOccured = false; tracker.TradeOccurred += (s, e) => { eventOccured = true; }; System.Threading.Thread.Sleep(25); Assert.True(eventOccured); } }
//Метод обработки ввода в TextBox только цифр private void OutCalc_KeyPress(object sender, KeyPressEventArgs e) { char num = e.KeyChar; //Реагирование только на цифры, запятая. if (!Char.IsDigit(num) && (num != 44)) { e.Handled = true; } //Нажатие кнопки умножения if (string.Compare(num.ToString(), "*") == 0) //Сравнение строки { Multiply.PerformClick(); //Запускаем метод нажатия на кнопку } //Нажатие деления if (string.Compare(num.ToString(), "/") == 0)//Сравнение строки { Share.PerformClick(); } //Нажатие вычитания if (string.Compare(num.ToString(), "-") == 0)//Сравнение строки { Minus.PerformClick(); } //Нажатие сложения if (string.Compare(num.ToString(), "+") == 0)//Сравнение строки { Plus.PerformClick(); } //Нажатия Enter if (num == 13) { Equally.PerformClick(); } }
public Share GetPriceForShare(string shortCode) { var random = new Random(); if (!LastPrices.ContainsKey(shortCode)) { var share = new Share { LastTradePrice = random.Next(0, 100000) / 100.0m, ShortCode = shortCode, TradeVolume = random.Next(0, 100000000), }; LastPrices.Add(shortCode, share); var timer = new Timer(1000); timer.Elapsed += (s, e) => { }; } return LastPrices[shortCode]; }
static void sort(xVector v) { int cnt = v.size(); for (int i = 0; i < cnt - 1; i++) { Share smallest = (Share)v.elementAt(i); int smallestIdx = i; for (int j = i + 1; j < cnt; j++) { Share item = (Share)v.elementAt(j); if (smallest.mSortParam > item.mSortParam) { smallest = item; smallestIdx = j; } } if (smallestIdx != i) { v.swap(i, smallestIdx); } } }
static void sortRevert(xVector v) { int cnt = v.size(); for (int i = 0; i < cnt - 1; i++) { Share biggest = (Share)v.elementAt(i); int biggestIdx = i; for (int j = i + 1; j < cnt; j++) { Share item = (Share)v.elementAt(j); if (biggest.mSortParam < item.mSortParam) { biggest = item; biggestIdx = j; } } if (biggestIdx != i) { v.swap(i, biggestIdx); } } }
public static void StartRecording() => Share.Start();
void AddFilelistsToShare(Share s) { General.AddCommonFilelistsToShare(s, currentDir + "MyFileLists\\"); }
public static Lot ToLot(Share share) => new Lot(share / 100);
/// <summary> /// パラメータを取得し、フィーチャーやトークン発行などを行う /// </summary> private void resetSwitch() { var ss = GetParamString().Split(new char[] { ',' }); var fis = GetRoot().GetChildFeatureInstance(); var tokenLidName = string.Empty; foreach (var s in ss) { var s2 = s.Trim(); if (s2.StartsWith("[")) // チェックボックス関連は関係ない { continue; } // トークン、シェアを設定する var com = s2.Split(new char[] { '=' }); if (com.Length == 2) { if (com[0].Trim().Equals("Command", StringComparison.CurrentCultureIgnoreCase)) { switch (com[1].Trim().ToUpper()) { case "REDRAW": Pane.Invalidate(null); break; case "KEEPOFF": ThreadSafe.SetChecked(_checkBox, false); _isOn = false; break; } } if (com[0].Trim().Equals("Token", StringComparison.CurrentCultureIgnoreCase)) { tokenLidName = com[1].Trim(); } if (com[0].Trim().Equals("ShareBool", StringComparison.CurrentCultureIgnoreCase)) { var b = (DataSharingManager.Boolean)Share.Get(com[1].Trim(), typeof(DataSharingManager.Boolean)); b.value = _isOn; } } else { // フィーチャーのEnabledを設定する foreach (FeatureBase fi in fis) { if (s2.StartsWith("@")) { if (fi.Name == s2.Substring(1)) { fi.Enabled = _isOn; } } else { if (fi.GetType().Name == s2) { fi.Enabled = _isOn; } } } } } // トークンを投げる(フィーチャーのEnableを設定した後) if (_isNoToken == false) { if (string.IsNullOrEmpty(tokenLidName) == false) { Token.Add(NamedId.FromName(tokenLidName), this); } } else { _isNoToken = false; } }
/// <summary> /// 切り替え /// </summary> public override void Start(NamedId who) { if (_tokenSwitch.Equals(who)) { var sw = (FeatureSwitch.TagFeatureSwitch)Share.Get("TokenChangeFeatureSwitches", typeof(FeatureSwitch.TagFeatureSwitch)); if (ID == sw.switchingFeatureID) { _isOn = sw.sw; if (_checkBox != null) { ThreadSafe.SetChecked(_checkBox, _isOn); } } else { return; } } else if (_tokenReadCompleted.Equals(who) == false) { if (string.IsNullOrEmpty(_interlockGroup)) { // UNDO/REDOしながら、スイッチ切り替え Persister[UNDO].StartChunk(GetType().Name + ".Start"); Persister[REDO].StartChunk(GetType().Name + ".Start"); Persister[UNDO].Save(new TagFeatureSwitch(this, _isOn), _featureDataID); _isOn = (_isOn ? false : true); Persister[REDO].Save(new TagFeatureSwitch(this, _isOn), _featureDataID); Persister[UNDO].EndChunk(); Persister[REDO].EndChunk(); } else { if (_isOn == false) { // UNDO/REDOしながら、グループの相手をOFFにする。 Persister[UNDO].StartChunk(GetType().Name + ".Start"); Persister[REDO].StartChunk(GetType().Name + ".Start"); var ig = (IList)_interlockGroups[_interlockGroup]; foreach (FeatureSwitch swf in ig) { if (object.ReferenceEquals(this, swf)) { continue; } if (swf._isOn != false) { Persister[UNDO].Save(new TagFeatureSwitch(swf, swf._isOn), _featureDataID); swf._isOn = false; Persister[REDO].Save(new TagFeatureSwitch(swf, swf._isOn), _featureDataID); if (swf._checkBox != null) { ThreadSafe.SetChecked(swf._checkBox, swf._isOn); } swf.resetSwitch(); } } Persister[UNDO].Save(new TagFeatureSwitch(this, _isOn), _featureDataID); _isOn = true; Persister[REDO].Save(new TagFeatureSwitch(this, _isOn), _featureDataID); Persister[UNDO].EndChunk(); Persister[REDO].EndChunk(); } } } if (_checkBox != null) { ThreadSafe.SetChecked(_checkBox, _isOn); } resetSwitch(); }
public override void CreateShare() { if (!fromXml) { throw new System.ArgumentException("This method cant be used when you created this object from this constructor"); } share = new Share(string.Empty); xmlBaseStream.Position = 0; XmlTextReader reader = null; string virtualDir = string.Empty; long created = 0; // If this list is comressed if (bz2) { System.IO.MemoryStream tmpStream = new System.IO.MemoryStream(); Utils.Compression.Bz2.Decompress(xmlBaseStream, tmpStream); tmpStream.Position = 0; reader = new XmlTextReader(tmpStream); } else { reader = new XmlTextReader(xmlBaseStream); } if (reader != null) { do { switch (reader.NodeType) { case XmlNodeType.Element: if (reader.HasAttributes) { if (reader.Name.Equals("File", StringComparison.OrdinalIgnoreCase)) { string name = reader.GetAttribute("Name"); long size = -1; try { size = long.Parse(reader.GetAttribute("Size")); } catch { } string tth = reader.GetAttribute("TTH"); Containers.ContentInfo ci = null; if (string.IsNullOrEmpty(tth)) { ci = new ContentInfo(ContentInfo.NAME, name); } else { ci = new ContentInfo(ContentInfo.TTH, tth); } ci.Size = size; #region Adding virtual dir if (true || changed > created) { created = DateTime.Now.Ticks; virtualDir = ""; string[] tmpDirs = dirs.ToArray(); for (int i = tmpDirs.Length - 1; i >= 0; i--) { virtualDir += tmpDirs[i] + @"\"; } } ci.Set(ContentInfo.VIRTUAL, virtualDir + name); ci.Set(ContentInfo.NAME, name); #endregion AddFile(ci); } else if (reader.Name.Equals("Directory", StringComparison.OrdinalIgnoreCase)) { // Add directory string name = reader.GetAttribute("Name"); if (!string.IsNullOrEmpty(name)) { StartDirectory(name); } } else if (reader.Name.Equals("FileListing", StringComparison.OrdinalIgnoreCase)) { generator = reader.GetAttribute("Generator"); cid = reader.GetAttribute("CID"); } } break; case XmlNodeType.EndElement: if (reader.Name.Equals("Directory")) { // Remove directory EndDirectory(); } break; } } while (reader.Read()); } }
public void Visit(Share share) { Tax += share.MonthlyTransaction * share.TaxApplicable; }
public ShareAdapter(Share sh) { Sh = sh; }
/// <summary> /// Creates a new share or updates an existing share on the device. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='deviceName'> /// The device name. /// </param> /// <param name='name'> /// The share name. /// </param> /// <param name='share'> /// The share properties. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task <Share> BeginCreateOrUpdateAsync(this ISharesOperations operations, string deviceName, string name, Share share, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(deviceName, name, share, resourceGroupName, null, cancellationToken).ConfigureAwait(false)) { return(_result.Body); } }
public override string ToString() { return(string.Format("MegacoolReceivedShareOpenedEvent(IsFirstSession={0}, " + "SenderUserId=\"{1}\", CreatedAt={2}, Share={3})", IsFirstSession ? "true" : "false", SenderUserId, CreatedAt.ToString("yyyy-MM-ddTHH:mm:ss"), Share == null ? null : Share.ToString())); }
public ClientShare(StratumClient client, Share share) { Client = client; Share = share; }
public virtual Result Create( Share share ) { if (IsShared( share )) return new Result( lang.get( "exHaveShared" ) ); return db.insert( share ); }
private List<ShareComment> getCommentsByShare( List<ShareComment> comments, Share share ) { List<ShareComment> results = new List<ShareComment>(); foreach (ShareComment c in comments) { if (c.Root.Id == share.Id) results.Add( c ); } return results; }
public static extern SafeFileHandle CreateFile(string lpFileName, Rights dwDesiredAccess, Share dwShareMode, IntPtr lpSecurityAttributes, Disposition dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile);
public ActionResult imPortExcel(HttpPostedFileBase excelfile, string companyId, string FacultyId) { var role = Convert.ToInt32(Session["Role"].ToString()); // Kiểm tra file đó có tồn tại hay không if (excelfile == null || excelfile.ContentLength == 0) { ViewBag.Error = "Thêm File mới<br /> "; } else { // kiểm tra đuôi file có phải là file Excel hay không if (excelfile.FileName.EndsWith("xls") || excelfile.FileName.EndsWith("xlsx")) { // Khai báo đường dẫn string path = Path.Combine("D:/", excelfile.FileName); // Tạo đối tượng COM. Tạo một đối tượng COM cho mọi thứ được tham chiếu Excel.Application application = new Excel.Application(); // Tạo application cái này là mở ms Excel Excel.Workbook workbook = application.Workbooks.Open(path); // Mở WorkBook Mở file Excel mình truyền vào Excel.Worksheet worksheet = (Excel.Worksheet)workbook.ActiveSheet; // Mở worksheet Mở sheet đầu tiên Excel.Range range = worksheet.UsedRange; //Lặp lại qua các hàng và cột và in ra bàn điều khiển khi nó xuất hiện trong tệp //excel is not zero based!! if (role == 3) { var schoolID = Session["SchoolID"].ToString(); for (int i = 2; i < range.Rows.Count; i++) { Person person = new Person(); string personID; do { personID = new Share().RandomText(); } while (new Share().FindPerson(personID) == false); person.PersonID = personID; person.LastName = ((Excel.Range)range.Cells[i, 3]).Text; person.FirstName = ((Excel.Range)range.Cells[i, 4]).Text; DateTime dateValue = DateTime.FromOADate(Convert.ToDouble(((Excel.Range)range.Cells[i, 5]).Value)); // Dòng code này có ý nghĩa là nó sẽ chuyển đối kiểu số thành ngày lại person.Birthday = dateValue; int gender = int.Parse(((Excel.Range)range.Cells[i, 6]).Text); person.Gender = Convert.ToBoolean(gender); person.Address = ((Excel.Range)range.Cells[i, 7]).Text; person.Phone = ((Excel.Range)range.Cells[i, 8]).Text; person.Email = ((Excel.Range)range.Cells[i, 9]).Text; person.SchoolID = schoolID; person.CompanyID = companyId; person.RoleID = 5; //listproducts.Add(product); new Share().InsertPerson(person); if (SendMailTK(personID)) { Intern intern = new Intern(); intern.PersonID = personID; intern.StudentCode = ((Excel.Range)range.Cells[i, 2]).Text; intern.Result = 0; InsertInt(intern); } } } else { var companyID = Session["CompanyID"].ToString(); for (int i = 2; i < range.Rows.Count; i++) { Person person = new Person(); string personID; do { personID = new Share().RandomText(); } while (new Share().FindPerson(personID) == false); person.PersonID = personID; person.LastName = ((Excel.Range)range.Cells[i, 3]).Text; person.FirstName = ((Excel.Range)range.Cells[i, 4]).Text; //person.Birthday = DateTime.ParseExact(((Excel.Range)range.Cells[i, 4]).Text,"yyyy/MM/dd",null); DateTime dateValue = DateTime.FromOADate(Convert.ToDouble(((Excel.Range)range.Cells[i, 5]).Value)); person.Birthday = dateValue; int gender = int.Parse(((Excel.Range)range.Cells[i, 6]).Text); //person.Gender = bool.Parse(Convert.ToUInt32(((Excel.Range)range.Cells[i, 5]).Value)); person.Gender = Convert.ToBoolean(gender); person.Address = ((Excel.Range)range.Cells[i, 7]).Text; person.Phone = ((Excel.Range)range.Cells[i, 8]).Text; person.Email = ((Excel.Range)range.Cells[i, 9]).Text; person.CompanyID = companyID; person.SchoolID = FacultyId; person.RoleID = 5; //listproducts.Add(product); new Share().InsertPerson(person); if (SendMailTK(personID)) { Intern intern = new Intern(); intern.PersonID = personID; intern.StudentCode = ((Excel.Range)range.Cells[i, 2]).Text; intern.Result = 0; InsertInt(intern); } } } //cleanup GC.Collect(); GC.WaitForPendingFinalizers(); //xuất các đối tượng com để dừng hoàn toàn quá trình excel chạy trong nền Marshal.ReleaseComObject(range); Marshal.ReleaseComObject(worksheet); //đóng lại và xuất thông tin workbook.Close(); Marshal.ReleaseComObject(workbook); //thoát và xuất thông tin application.Quit(); Marshal.ReleaseComObject(application); //ViewBag.ListProduct = listproducts; //dem = listproducts.Count(); ViewBag.Error = "Thêm thành công<br /> "; } else { ViewBag.Error = "File không hợp lệ<br /> "; } } if (role == 3) { var list = new Share().listOrgan(2).ToList(); ViewBag.listOrganization = new SelectList(list, "ID", "Name"); } else { var list = new Share().listOrgan(6).ToList(); ViewBag.listOrganization = new SelectList(list, "ID", "Name"); } return(View("imPortExcel")); }
public void SaveComment() { if (ctx.viewer.IsLogin == false) { echoRedirect(lang("exPlsLogin")); return; } String content = ctx.Post("content"); if (strUtil.IsNullOrEmpty(content)) { echoError(lang("exContent")); return; } int rootId = ctx.PostInt("rootId"); int parentId = ctx.PostInt("parentId"); //content = strUtil.CutString( content, Microblog.ContentLength ); Share share = shareService.GetById(rootId); ShareComment c = new ShareComment(); c.Root = share; c.ParentId = parentId; c.User = (User)ctx.viewer.obj; c.Ip = ctx.Ip; c.Content = content; //String shareLink = Link.To( share.Creator, Show, share.Id ); // 应该是接收者可以查看的,所以网址在接收者后台中 String rootShareLink = Link.To(share.Creator, new ShareController().Show, share.Id); String parentShareLink = null; if (parentId > 0) { ShareComment pshare = shareService.GetCommentById(parentId); parentShareLink = Link.To(pshare.User, new ShareController().Show, share.Id); } shareService.InsertComment(c, rootShareLink, parentShareLink); String str = @" <table style=""width: 95%; margin:5px 0px 5px 0px;background:#ebf3f7;""> <tr> <td style=""width:38px;""><a href=""{0}""><img src=""{1}"" style=""width:32px;""/></a></td> <td style=""vertical-align:top;""> <div><a href=""{0}"">{2}</a> <span class=""note"">" + lang("postedAt") + @" {3}</span></div> <div style=""margin-top:5px;"">{4}</div> </td> </tr> </table> "; String msg = string.Format(str, Link.ToMember(ctx.viewer.obj), ctx.viewer.obj.PicSmall, ctx.viewer.obj.Name, cvt.ToTimeString(DateTime.Now), content ); if (parentId == 0) { echoHtmlTo("shareComments" + rootId, msg); } else { echoHtmlTo("commentContent" + parentId, msg); } }
protected virtual (Share Share, string BlockHex) ProcessShareInternal( StratumClient worker, string extraNonce2, uint nTime, uint nonce, uint?versionBits) { var context = worker.ContextAs <BitcoinWorkerContext>(); var extraNonce1 = context.ExtraNonce1; // build coinbase var coinbase = SerializeCoinbase(extraNonce1, extraNonce2); Span <byte> coinbaseHash = stackalloc byte[32]; coinbaseHasher.Digest(coinbase, coinbaseHash); // hash block-header var headerBytes = SerializeHeader(coinbaseHash, nTime, nonce, context.VersionRollingMask, versionBits); Span <byte> headerHash = stackalloc byte[32]; headerHasher.Digest(headerBytes, headerHash, (ulong)nTime, BlockTemplate, coin, networkParams); var headerValue = new uint256(headerHash); // calc share-diff var shareDiff = (double)new BigRational(BitcoinConstants.Diff1, headerHash.ToBigInteger()) * shareMultiplier; var stratumDifficulty = context.Difficulty; var ratio = shareDiff / stratumDifficulty; // check if the share meets the much harder block difficulty (block candidate) var isBlockCandidate = headerValue <= blockTargetValue; // test if share meets at least workers current difficulty if (!isBlockCandidate && ratio < 0.99) { // check if share matched the previous difficulty from before a vardiff retarget if (context.VarDiff?.LastUpdate != null && context.PreviousDifficulty.HasValue) { ratio = shareDiff / context.PreviousDifficulty.Value; if (ratio < 0.99) { throw new StratumException(StratumError.LowDifficultyShare, $"low difficulty share given ({shareDiff})"); } // use previous difficulty stratumDifficulty = context.PreviousDifficulty.Value; } else { throw new StratumException(StratumError.LowDifficultyShare, $"low difficulty share ({shareDiff})"); } } var result = new Share { BlockHeight = BlockTemplate.Height, NetworkDifficulty = Difficulty, Difficulty = stratumDifficulty / shareMultiplier, }; if (isBlockCandidate) { result.IsBlockCandidate = true; Span <byte> blockHash = stackalloc byte[32]; blockHasher.Digest(headerBytes, blockHash, nTime); result.BlockHash = blockHash.ToHexString(); var blockBytes = SerializeBlock(headerBytes, coinbase); var blockHex = blockBytes.ToHexString(); return(result, blockHex); } return(result, null); }
public void RegisterShare(Share share) { throw new NotImplementedException(); }
protected virtual async Task <(bool Accepted, string CoinbaseTransaction)> SubmitBlockAsync(Share share, string blockHex) { var results = await daemon.ExecuteBatchAnyAsync( hasSubmitBlockMethod ?new DaemonCmd(BitcoinCommands.SubmitBlock, new[] { blockHex }) : new DaemonCmd(BitcoinCommands.GetBlockTemplate, new { mode = "submit", data = blockHex }), new DaemonCmd(BitcoinCommands.GetBlock, new[] { share.BlockHash })); var submitResult = results[0]; var submitError = submitResult.Error?.Message ?? submitResult.Error?.Code.ToString(CultureInfo.InvariantCulture) ?? submitResult.Response?.ToString(); if (!string.IsNullOrEmpty(submitError)) { logger.Warn(() => $"[{LogCat}] Block {share.BlockHeight} submission failed with: {submitError}"); notificationService.NotifyAdmin("Block submission failed", $"Pool {poolConfig.Id} {(!string.IsNullOrEmpty(share.Source) ? $"[{share.Source.ToUpper()}] " : string.Empty)}failed to submit block {share.BlockHeight}: {submitError}"); return(false, null); } var acceptResult = results[1]; var block = acceptResult.Response?.ToObject <DaemonResponses.Block>(); var accepted = acceptResult.Error == null && block?.Hash == share.BlockHash; if (!accepted) { logger.Warn(() => $"[{LogCat}] Block {share.BlockHeight} submission failed for pool {poolConfig.Id} because block was not found after submission"); notificationService.NotifyAdmin($"[{share.PoolId.ToUpper()}]-[{share.Source}] Block submission failed", $"[{share.PoolId.ToUpper()}]-[{share.Source}] Block {share.BlockHeight} submission failed for pool {poolConfig.Id} because block was not found after submission"); } return(accepted, block?.Transactions.FirstOrDefault()); }
/// <summary> /// 初期化 /// </summary> public override void OnInitInstance() { _interlockGroups = (IDictionary)Share.Get("SwitchInterlockGroup", typeof(Hashtable)); }
public ShareDTO ToDTO(Share share) { return(new ShareDTO(share)); }
// code | _ref | KL1 | G1 |= GiaKhop | KLKhop | TongKL =| KL1 | G1 |=== TB | Cao | Thap virtual protected void updateQuote() { if (getID() < 0) { return; } Context ctx = Context.getInstance(); stCell c; if (getID() == 0) { // code setCellValue(0, "▼ Mã\nTC", C.COLOR_ORANGE); setCellValue(2, "M3/KL", C.COLOR_GRAY); setCellValue(3, "M2/KL", C.COLOR_GRAY); setCellValue(4, "M1/KL", C.COLOR_GRAY); setCellValue(5, "Khớp", C.COLOR_GRAY); setCellValue(6, "+/-", C.COLOR_GRAY); setCellValue(7, "B1/KL", C.COLOR_GRAY); setCellValue(8, "B2/KL", C.COLOR_GRAY); setCellValue(9, "B3/KL", C.COLOR_GRAY); setCellValue(10, "H/L", C.COLOR_GRAY); setCellValue(11, "TổngKL", C.COLOR_GRAY); /* * c = getCellAt(11); * if (c != null) * { * c.text2 = "DưB"; * c.textColor2 = C.COLOR_GRAY; * } */ if (sortType == ShareSortUtils.SORT_DUMUA_DUBAN) { setCellValue(12, "▼ Dư\nM/B", C.COLOR_ORANGE); } else { setCellValue(12, "▼ " + ShareSortUtils.sortTypeToString(sortType), C.COLOR_ORANGE); } } if (getID() == 0) { return; } String code = (String)getUserData(); if (code == null) { return; } stPriceboardState item = ctx.mPriceboard.getPriceboard(code); stPriceboardState ps = item; if (item == null) { return; } Share share = ctx.mShareManager.getShare(ps.id); if (share == null) { return; } String s; // code uint color; setCellValue(0, code, C.COLOR_WHITE); addCellValue1(0, String.Format("{0:F2}", item.getRef()), C.COLOR_YELLOW); float _ref = item.getRef(); int j = 0; float v; int[] rbc = { 2, 3, 4 }; // remain buy col float[] rb = { ps.getRemainBuyPrice2(), ps.getRemainBuyPrice1(), ps.getRemainBuyPrice0() }; int[] rbv = { ps.getRemainBuyVolume2(), ps.getRemainBuyVolume1(), ps.getRemainBuyVolume0() }; int[] rsc = { 7, 8, 9 }; float[] rs = { ps.getRemainSellPrice0(), ps.getRemainSellPrice1(), ps.getRemainSellPrice2() }; int[] rsv = { ps.getRemainSellVolume0(), ps.getRemainSellVolume1(), ps.getRemainSellVolume2() }; // mua1, mua2, mua3 for (j = 0; j < 3; j++) { // price color = ctx.valToColorF(rb[j], item.getCe(), item.getRef(), item.getFloor()); setCellValue(rbc[j], String.Format("{0:F2}", rb[j]), color); // vol s = volumeToString(rbv[j]); addCellValue1(rbc[j], s); } // Khop float currentPrice = item.getCurrentPrice(); int currentVol = item.getCurrentVolume(); color = ctx.valToColorF(currentPrice, item.getCe(), item.getRef(), item.getFloor()); setCellValue(5, String.Format("{0:F2}", currentPrice), color); s = volumeToString(currentVol); addCellValue1(5, s); // change +/- v = currentPrice - item.getRef(); s = String.Format("{0:F2}", (float)v); if (currentPrice == 0) { s = "-"; } setCellValue(6, s, color); // sell1, sell2, sell3 for (j = 0; j < 3; j++) { // price color = ctx.valToColorF(rs[j], item.getCe(), item.getRef(), item.getFloor()); setCellValue(rsc[j], String.Format("{0:F2}", rs[j]), color); // vol s = volumeToString(rsv[j]); addCellValue1(rsc[j], s); } // cao - thap setCellValue(10, String.Format("{0:F2}", item.getMax()), ctx.valToColorF(item.getMax(), item.getCe(), item.getRef(), item.getFloor())); addCellValue1(10, String.Format("{0:F2}", item.getMin()), ctx.valToColorF(item.getMin(), item.getCe(), item.getRef(), item.getFloor())); // total volume // s = volumeToString(item.getTotalVolume()); // setCellValue(11, s, C.COLOR_WHITE); mVolumeColumn = 11; // cung - cau if (sortType == ShareSortUtils.SORT_DUMUA_DUBAN) { int buy = item.getRemainBuyVolume0() + item.getRemainBuyVolume1() + item.getRemainBuyVolume2(); int sell = item.getRemainSellVolume0() + item.getRemainSellVolume1() + item.getRemainSellVolume2(); String sbuy = volumeToString(buy); String ssell = volumeToString(sell); setCellValue(12, sbuy, C.COLOR_ORANGE); c = getCellAt(12); if (c != null) { c.text2 = ssell; c.textColor2 = C.COLOR_ORANGE; } } else { setCellValue(12, share.mCompareText, C.COLOR_ORANGE); c = getCellAt(12); if (c != null) { c.text2 = null; c.textColor2 = C.COLOR_ORANGE; } } }
public async Task DeleteShareAsync(Share share) { _context.Shares.Remove(share); await _context.SaveChangesAsync(); }
private void bindOne( IBlock block, Share share ) { block.Set( "share.Id", share.Id ); block.Set( "share.DataType", share.DataType ); block.Set( "share.UserFace", share.Creator.PicSmall ); block.Set( "share.UserLink", toUser( share.Creator ) ); String creatorInfo = getCreatorInfos( share.Creator ); String feedTitle = feedService.GetHtmlValue( share.TitleTemplate, share.TitleData, creatorInfo ); block.Set( "share.Title", feedTitle ); block.Set( "commentList", loadHtml( new ShareCommentsController().commentList, share.Id ) ); String feedBody = feedService.GetHtmlValue( share.BodyTemplate, share.BodyData, creatorInfo ); block.Set( "share.Body", feedBody ); block.Set( "share.BodyGeneral", getComment( share.BodyGeneral ) ); block.Set( "share.Created", share.Created ); }
public async Task <List <SharedObject> > GetShareContentAsync(Share share) { var list = await _context.SharedObjects.Where(s => s.ShareId == share.Id).ToListAsync(); return(list); }
void AddFilelistsToShare(Share s) { // This will add common filelists to share and save them in directory specified. General.AddCommonFilelistsToShare(s, currentDir + "MyFileLists\\"); }
public ActionResult Create(InternClass per) { var role = Convert.ToInt32(Session["Role"].ToString()); if (ModelState.IsValid) { WebDatabaseEntities database = new WebDatabaseEntities(); Person person = new Person(); string personID; do { personID = new Share().RandomText(); } while (new Share().FindPerson(personID) == false); person.PersonID = personID; database.Person.Add(person); person.RoleID = 5; person.LastName = per.LastName; person.FirstName = per.FirstName; person.Birthday = per.Birthday; person.Gender = per.Gender; person.Address = per.Address; person.Phone = per.Phone; person.Email = per.Email; if (role == 3) { var schoolID = Session["SchoolID"].ToString(); person.SchoolID = schoolID; person.CompanyID = per.CompanyID; } else { var companyID = Session["CompanyID"].ToString(); person.SchoolID = per.FacultyId; person.CompanyID = companyID; } if (new Share().InsertPerson(person)) { if (SendMailTK(personID)) { Intern intern = new Intern(); intern.PersonID = personID; intern.StudentCode = per.StudentCode; if (per.InternshipID != null) { intern.InternshipID = per.InternshipID; } intern.Result = 0; InsertInt(intern); ModelState.AddModelError("", "Thêm Thực tập sinh thành công"); } else { ModelState.AddModelError("", "Không thể gửi Email kích hoạt"); } } else { ModelState.AddModelError("", "Thêm Thực tập sinh thất bại"); } } SetViewBag(); SetViewBagS(); SetViewBagG(); if (role != 3) { SetViewBagI(); } return(View("Create")); }
public static void StopRecording() => Share.Stop().Wait();
public virtual Boolean IsShared( Share share ) { List<Share> list = Share.find( "Creator.Id=:cid and HashData=:data" ) .set( "cid", share.Creator.Id ) .set( "data", share.HashData ) .list(); return list.Count > 0; }
private void ButtonScanCustom_Clicked(object sender, EventArgs e) { var overlay = new AbsoluteLayout { //WidthRequest = 200, //HeightRequest = 200, HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand, }; var stack = new StackLayout { HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand }; var grid = new Grid(); { grid.VerticalOptions = LayoutOptions.FillAndExpand; grid.HorizontalOptions = LayoutOptions.FillAndExpand; grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) }); grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(2, GridUnitType.Star) }); grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) }); grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); grid.Children.Add(new BoxView { VerticalOptions = LayoutOptions.Fill, HorizontalOptions = LayoutOptions.FillAndExpand, BackgroundColor = Color.Black, Opacity = 0.7, }, 0, 0); grid.Children.Add(new BoxView { VerticalOptions = LayoutOptions.Fill, HorizontalOptions = LayoutOptions.FillAndExpand, BackgroundColor = Color.Black, Opacity = 0.7, }, 0, 2); grid.Children.Add(new BoxView { VerticalOptions = LayoutOptions.Center, HorizontalOptions = LayoutOptions.FillAndExpand, HeightRequest = 3, BackgroundColor = Color.FromHex("#1976D2"), Opacity = 0.6, }, 0, 1); } var torch = new Button { //Text = "Let there be light!", Text = "Torch", // Enable "Material" Visual on C# Visual = VisualMarker.Material, //Source = "sculpturetorch.png", //HorizontalOptions = LayoutOptions.Start, //VerticalOptions = LayoutOptions.End, //WidthRequest = 80, //HeightRequest = 80, //Opacity = 1, BackgroundColor = Color.FromHex("#2E7ACE"), //Image = "torch.img", }; AbsoluteLayout.SetLayoutFlags(stack, AbsoluteLayoutFlags.All); AbsoluteLayout.SetLayoutBounds(stack, new Rectangle(0f, 0f, 1f, 1f)); AbsoluteLayout.SetLayoutFlags(torch, AbsoluteLayoutFlags.PositionProportional); AbsoluteLayout.SetLayoutBounds(torch, new Rectangle(0, 1, AbsoluteLayout.AutoSize, AbsoluteLayout.AutoSize)); overlay.Children.Add(stack); overlay.Children.Add(torch); stack.Children.Add(grid); //Content = stack; var batteryLevel = CrossBattery.Current.RemainingChargePercent; var status = CrossBattery.Current.Status; torch.Clicked += async delegate { if (batteryLevel > 40 || status == Plugin.Battery.Abstractions.BatteryStatus.Charging) { scanPage.ToggleTorch(); } if (status == Plugin.Battery.Abstractions.BatteryStatus.NotCharging || batteryLevel < 40) { var notificator = DependencyService.Get <IToastNotificator>(); var androidOptions = new AndroidOptions { DismissText = "" }; var options = new NotificationOptions() { Title = "BatteryLow", AndroidOptions = androidOptions }; await notificator.Notify(options); } }; //scanPage = new ZXingScannerPage(new MobileBarcodeScanningOptions //{ AutoRotate = false, TryHarder = true}, customOverlay: customOverlay); //Not using customoverlay scanPage = new ZXingScannerPage(new MobileBarcodeScanningOptions { AutoRotate = false, TryHarder = true }, customOverlay: overlay); //scanPage = new ZXingScannerView //{ // HorizontalOptions = LayoutOptions.FillAndExpand, // VerticalOptions = LayoutOptions.FillAndExpand, // AutomationId = "zxingScannerView", //}; Navigation.PushModalAsync(scanPage); // Work with the result scanPage.OnScanResult += (result) => { var clipshit = result.Text; Clipboard.SetTextAsync(result.Text); Clipboard.GetTextAsync(); scanPage.IsScanning = false; // Action starts Device.BeginInvokeOnMainThread(async() => { await Navigation.PopModalAsync(); //if (clipshit != null) //if (result.Text.StartsWith("http")) string input = result.Text; //Regex regex = new Regex(@"https?://[-_.!~*'a-zA-Z0-9;/?:@&=+$,%#]+"); Match match = Regex.Match(input, @"https?://[-_.!~*'a-zA-Z0-9;/?:@&=+$,%#]+"); //return regex.Matches(strInput); if (match.Success) { var result2 = await DisplayAlert("URL detected.", "Wanna Open Browser?", "yes", "no"); if (result2 == true) { //var intent = new Intent(Intent.ActionMain); //intent.SetComponent(new ComponentName("com.catchingnow.tinyclipboardmanager", "com.catchingnow.tinyclipboardmanager.MainActivity")); //StartActivity(intent); Device.OpenUri(new Uri(result.Text)); } if (result2 == false) { //await Navigation.PopAsync(); //await DisplayAlert("みじっそう", "です", "さーせん"); var notificator = DependencyService.Get <IToastNotificator>(); var androidOptions = new AndroidOptions { DismissText = "Cancel" }; var options = new NotificationOptions() { Title = "Launching Share", AndroidOptions = androidOptions, }; var resultt = await notificator.Notify(options); if (!(resultt.Action == NotificationAction.Dismissed)) { await Share.RequestAsync(new ShareTextRequest(result.Text)); } else { Android.Widget.Toast.MakeText(Android.App.Application.Context, "Cancelled", Android.Widget.ToastLength.Short).Show(); } //DependencyService.Get<IDeviceService>().PlayVibrate(); //var duration = TimeSpan.FromSeconds(1); //Vibration.Vibrate(duration); } } else { //await Navigation.PopAsync(); var result3 = await DisplayAlert("Seems like it's not URL", "Share result?", "Yes", "No"); if (result3 == true) { await Share.RequestAsync(new ShareTextRequest(result.Text)); } if (result3 == false) { Android.Widget.Toast.MakeText(Android.App.Application.Context, "Result copied to Clipboard", Android.Widget.ToastLength.Short).Show(); } } //DependencyService.Get<IDeviceService>().PlayVibrate(); }); }; }
public void CreateShare(Share share) { Logger.ServiceLog.Info("Create share with user id: {0} and file id: {1}", share.User.Id, share.File.Id); _sharesRepository.Add(share); }
static public RowFilterResult createRowQuoteList(Share share, xIEventListener listener) { RowFilterResult row = new RowFilterResult(listener, share); return(row); }
/// <summary> /// Creates a new share or updates an existing share on the device. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='deviceName'> /// The device name. /// </param> /// <param name='name'> /// The share name. /// </param> /// <param name='share'> /// The share properties. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> public static Share BeginCreateOrUpdate(this ISharesOperations operations, string deviceName, string name, Share share, string resourceGroupName) { return(operations.BeginCreateOrUpdateAsync(deviceName, name, share, resourceGroupName).GetAwaiter().GetResult()); }