protected void btnLogin_Click(object sender, ImageClickEventArgs e) { if (txtUserName.Text.Trim() == "admin" && txtPwd.Text.Trim() == "admin") { Response.Redirect("~/default.aspx"); } User user = new User(); user.UserID = txtUserName.Text.Trim(); user.UserPWD = txtPwd.Text; BaseInfo baseInfo = new BaseInfo(); StatisticInfo sa = new StatisticInfo(); if (baseInfo.Login(user)) { Session["user"] = user; FormsAuthentication.SetAuthCookie(user.UserID, false); Response.Redirect("~/default.aspx"); } else { lblmessage.Text = "用户名或密码错误!"; txtPwd.Text = ""; txtPwd.Focus(); } }
public static BaseInfo gI () { if(instance == null) { instance = new BaseInfo (); } return instance; }
private bool CustomerIsOnCurrentSite(BaseInfo customerInfo) { var currentSiteID = SiteContext.CurrentSiteID; if (customerInfo.GetIntegerValue("CustomerSiteID", 0) == currentSiteID) { return true; } var userID = customerInfo.GetIntegerValue("CustomerUserID", 0); return (userID > 0) && (UserSiteInfoProvider.GetUserSiteInfo(userID, currentSiteID) != null); }
private DataClassInfo FindDataClass(BaseInfo item) { switch (item.TypeInfo.ObjectType) { case BizFormInfo.OBJECT_TYPE: var classId = ValidationHelper.GetInteger(item.GetValue("FormClassID"), 0); return DataClassInfoProvider.GetDataClassInfo(classId); case DocumentTypeInfo.OBJECT_TYPE_DOCUMENTTYPE: case CustomTableInfo.OBJECT_TYPE_CUSTOMTABLE: var className = ValidationHelper.GetString(item.GetValue("ClassName"), String.Empty); return DataClassInfoProvider.GetDataClassInfo(className); } return null; }
/// <summary> /// Sets source and alternative text for image element. If image Guid is not set, uses default image according to given base info. /// </summary> /// <param name="baseInfo">Edited object, determines default image if image guid is not specified</param> private void SetImageAttributes(BaseInfo baseInfo) { Guid imageGuid = ValidationHelper.GetGuid(Value, Guid.Empty); if (imageGuid == Guid.Empty) { var manager = new DefaultClassThumbnail(baseInfo.TypeInfo.ObjectType); imageGuid = manager.GetDefaultClassThumbnailGuid() ?? Guid.Empty; } string imageUrl = MetaFileURLProvider.GetMetaFileUrl(imageGuid, string.Empty); imageUrl = URLHelper.UpdateParameterInUrl(imageUrl, "maxsidesize", "256"); imgPreview.Src = imageUrl; imgPreview.Alt = GetString("general.objectimage"); }
public SolutionAttrTable(Solution solution) { _solution = solution; baseInfo = new BaseInfo("基本信息"); heatInfos = new CustomAttrCollection(); int heattag = 1; if (solution != null) { if (solution.HeatProducers.Count != 0) { foreach (var heatproducer in HeatSourceLayoutApp.currentSolution.HeatProducers.Values) { heatInfos.Add(new HeatProducerInfo("热源" + (heattag++), heatproducer)); } } totalInfo = new TotoalInfo("工程总表", _solution); } }
private void ParseActor(BaseInfo info) { parser.ReadLine(); var h = parser.ReadFloat(); // capsule height parser.ReadLine(); var r = parser.ReadFloat(); // capsule radius builder.BeginComponent("PhysicsComponent"); builder.AddParameter("type", "capsule"); builder.AddParameter("radius", r.ToString(CultureInfo.InvariantCulture)); builder.AddParameter("height", h.ToString(CultureInfo.InvariantCulture)); builder.EndComponent(); var fn = Path.GetFileNameWithoutExtension(info.AssetName); var path = Path.GetDirectoryName(info.AssetName); builder.AddAsset(fn + ".rest", false, info.AssetName); builder.BeginComponent("BlendAnimationController"); builder.AddParameter("restPose", fn + ".rest"); var sb = new StringBuilder(); foreach (var anim in Directory.GetFiles(baseDir + path, "anims/*.smd", SearchOption.AllDirectories)) { var animname = Path.GetFileNameWithoutExtension(anim); var alias = fn + ".animation." + animname; builder.AddAsset(alias, false, anim.Remove(0, baseDir.Length).Replace('\\', '/')); if (sb.Length != 0) sb.Append(";"); sb.Append(alias); } builder.AddParameter("animations", sb.ToString()); builder.EndComponent(); builder.BeginComponent("MotionComponent"); builder.EndComponent(); builder.BeginComponent("HealthComponent"); builder.AddParameter("hp", info.Name == "heroe" ? "100": "3"); builder.EndComponent(); }
protected void Page_Load(object sender, EventArgs e) { if (StopProcessing) { // No actions if processing is stopped } else { editElem.OnSelectionChanged += editElem_OnSelectionChanged; // Create object types (BaseInfo) obj = ModuleManager.GetObject(ObjectType); objProvider = ModuleManager.GetObject(BindingObjectType); // Automatic compute target object type if (String.IsNullOrEmpty(TargetObjectType)) { var providerTypeInfo = objProvider.TypeInfo; // Search for parent in TYPEINFO var parent = providerTypeInfo.ParentObjectType; if ((parent != String.Empty) && (parent != ObjectType)) { // If parent is different from control's object type use it. TargetObjectType = parent; } else { // Otherwise search in site object var siteObject = providerTypeInfo.SiteIDColumn; if ((siteObject != String.Empty) && (siteObject != ObjectTypeInfo.COLUMN_NAME_UNKNOWN)) { TargetObjectType = SiteInfo.OBJECT_TYPE; } else { // If site object not specified use bindings. Find first binding dependency and use it's object type var od = providerTypeInfo.ObjectDependencies.FirstOrDefault(x => x.DependencyType == ObjectDependencyEnum.Binding); if (od != null) { TargetObjectType = od.DependencyObjectType; } } } } objTarget = ModuleManager.GetObject(TargetObjectType); //Check view permission if (!CheckViewPermissions(objProvider)) { editElem.StopProcessing = true; editElem.Visible = false; return; } // Check edit permissions if (!CheckEditPermissions(objProvider)) { editElem.Enabled = false; ShowError(GetString("ui.notauthorizemodified")); } // Validate input data if (!ValidateInputData()) { return; } // Set uni selector editElem.ObjectType = TargetObjectType; editElem.ResourcePrefix = ResourcePrefix; editElem.WhereCondition = DialogWhereCondition; if (!RequestHelper.IsPostBack()) { // Set values editElem.Value = CurrentValues; } } }
public void CreateInfoPlayer(PlayerInfo pl) { body.SetActive(true); setMoneyChip(0); gender = pl.gender; //setGendel(gender); setName(pl.name); setDisplayeName(pl.displayname); folowMoney = pl.folowMoney; lb_money.gameObject.SetActive(true); if (folowMoney.ToString().Length < 7) { lb_money.text = ("" + BaseInfo.formatMoneyDetailDot(folowMoney)); } else { lb_money.text = ("" + BaseInfo.formatMoneyNormal(folowMoney)); } setMaster(pl.isMaster); if (!isMaster()) { //setReady(pl.isReady); isReadys = pl.isReady; } setInvite(pl.isVisibleInvite); serverPos = pl.posServer; setSit(true); isSits = true; isPlayings = false; if (cardHand != null) { cardHand.removeAllCard(); } if (sp_sap3chi != null) { sp_sap3chi.gameObject.SetActive(false); } if (sp_action != null) { sp_action.gameObject.SetActive(false); } if (sp_xoay != null) { sp_xoay.gameObject.SetActive(false); } if (sp_thang != null) { sp_thang.gameObject.SetActive(false); } if (sp_baoSam != null) { sp_baoSam.gameObject.SetActive(false); } if (sp_xepXong != null) { sp_xepXong.gameObject.SetActive(false); } if (sp_lung != null) { sp_lung.gameObject.SetActive(false); } if (lb_money_result2 != null) { lb_money_result2.SetActive(false); } //www = null; ///isOneAvata = false; if (pl.link_avatar != "") { //www = new WWW(pl.link_avatar); // img_avatar.gameObject.SetActive(false); // raw_avatar.gameObject.SetActive(true); StartCoroutine(getAvata(pl.link_avatar)); } else { img_avatar.gameObject.SetActive(true); raw_avatar.gameObject.SetActive(false); //img_avatar.sprite = Res.getAvataByID(pl.idAvata);//Res.list_avata[idAvata + 1]; LoadAssetBundle.LoadSprite(img_avatar, Res.AS_UI_AVATA, "" + pl.idAvata); } }
protected void usObjects_OnSelectionChanged(object sender, EventArgs e) { // Get new selection from selector string newValues = ValidationHelper.GetString(usObjects.Value, null); // Compare with previous selection and get items to remove string items = DataHelper.GetNewItemsInList(newValues, currentValues); if (!String.IsNullOrEmpty(items)) { string[] newItems = items.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); // Remove items from site foreach (string item in newItems) { // Get identifier of parent object int parentId = ValidationHelper.GetInteger(item, 0); // Get binding object based on type BaseInfo bindingObj = CMSObjectHelper.GetObject(BindingObjectType); // Initialize values of removed object to allow recognition bindingObj.SetValue(bindingObj.TypeInfo.SiteIDColumn, SiteID); bindingObj.SetValue(bindingObj.TypeInfo.ParentIDColumn, parentId); // Get existing object if binding object has identifying column if (bindingObj.TypeInfo.IDColumn != TypeInfo.COLUMN_NAME_UNKNOWN) { bindingObj = bindingObj.Generalized.GetExisting(); } // Delete the binding bindingObj.Generalized.DeleteObject(); } } // Compare with previous selection and get items to add items = DataHelper.GetNewItemsInList(currentValues, newValues); if (!String.IsNullOrEmpty(items)) { string[] newItems = items.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); // Add all new items to site foreach (string item in newItems) { // Get identifier of parent object int parentId = ValidationHelper.GetInteger(item, 0); // Get binding object based on type BaseInfo bindingObj = CMSObjectHelper.GetObject(BindingObjectType); // Initialize values bindingObj.SetValue(bindingObj.TypeInfo.SiteIDColumn, SiteID); bindingObj.SetValue(bindingObj.TypeInfo.ParentIDColumn, parentId); // Insert new object bindingObj.Generalized.SetObject(); } } ShowChangesSaved(); }
public bool SendPhoneAPNS(BaseInfo baseInfo) { PhoneGCMInfo info = (PhoneGCMInfo)baseInfo; JSONInfo Info1 = new JSONInfo(); subJSONInfo Info2 = new subJSONInfo(); JSONResult Info3 = new JSONResult(); ArrayList _GetPhoneRegIDData = new ArrayList(); ArrayList _GetCarAlarmData = new ArrayList(); ArrayList _GetRuleInfoData = new ArrayList(); ArrayList _IOSRegIDData = new ArrayList(); ArrayList _RegIDData = new ArrayList(); _GetCarAlarmData.Add(info.DeviceID); IDataReader reader1 = DataProvider.Instance().ChkPhoneDriverInfoDB(_GetCarAlarmData);//FMS_PhoneDriverInfo_Fetch;return CarNo,Driver if (reader1.Read()) { Info1.type = "check"; Info2.CarNo = reader1.GetString(0); Info2.Driver = reader1.GetString(1); } CBO.CloseDataReader(reader1, true); _GetRuleInfoData.Add(info.AlertRuleID); IDataReader reader2 = DataProvider.Instance().ChkPhoneRuleDB(_GetRuleInfoData);//FMS_PhoneRule_Fetch;return RuleName,AlarmType,Severity if (reader2.Read()) { Info2.AlertDate = info.EventTime; Info2.RuleName = reader2.GetString(0); Info2.AlarmType = reader2.GetString(1); Info2.Severity = reader2.GetString(2); } CBO.CloseDataReader(reader2, true); StringBuilder _sb = new StringBuilder(); _sb.Append("警報日期:"); _sb.Append(Info2.AlertDate); _sb.Append("\\n"); _sb.Append("類型/嚴重度:"); if (Info2.Severity.Equals("3")) { _sb.Append(Info2.AlarmType + " / [嚴重]"); } else if (Info2.Severity.Equals("2")) { _sb.Append(Info2.AlarmType + " / [一般]"); } else { _sb.Append(Info2.AlarmType + " / [輕度]"); } _sb.Append("\\n"); _sb.Append("名稱:"); _sb.Append(Info2.RuleName); _sb.Append("\\n"); _sb.Append("車號/駕駛人:"); _sb.Append(Info2.CarNo + " / " + Info2.Driver); string output = _sb.ToString(); // string output = "警報日期:2015/03/04 11:55:00 \\n類型/嚴重度:超速 / [嚴重]\\n名稱:連續超速70km 3分鐘\\n車號/駕駛人:kw-car03 / 易大師"; _GetPhoneRegIDData.Add(info.AlertRuleID); _GetPhoneRegIDData.Add(info.DeviceID); IDataReader reader = DataProvider.Instance().GetAPNSDB(_GetPhoneRegIDData);//FMS_PhoneGCM_Fetch;return UserId,RegisterID,Phone_Mail_Logic APNSSender _apnsSender = new APNSSender(); string strResultJson; while (reader.Read()) { info.userID = reader.GetInt32(0).ToString(); info.RegID = reader.GetString(1); strResultJson = _apnsSender.SendAPNS(info.RegID, output); //save log record CreatePushNoticeLog(info, output, "Apple"); } CBO.CloseDataReader(reader, true); return true; }
/// <summary> /// Returns value of the given object column. /// </summary> /// <param name="info">Object data</param> /// <param name="columnName">Column name</param> private static object GetColumnValue(BaseInfo info, string columnName) { if ((info != null) && info.ContainsColumn(columnName)) { return info.GetValue(columnName); } return null; }
protected void Page_Load(object sender, EventArgs e) { eObject = UIContext.EditedObject as BaseInfo; // If saved is found in query string if (!RequestHelper.IsPostBack() && (QueryHelper.GetInteger("saved", 0) == 1)) { ShowChangesSaved(); } string before = String.Empty; string after = String.Empty; String objectType = UIContextHelper.GetObjectType(UIContext); switch (objectType.ToLowerCSafe()) { case "cms.webpart": defaultValueColumName = "WebPartDefaultValues"; before = PortalFormHelper.GetWebPartProperties(WebPartTypeEnum.Standard, PropertiesPosition.Before); after = PortalFormHelper.GetWebPartProperties(WebPartTypeEnum.Standard, PropertiesPosition.After); defaultSet = FormHelper.CombineFormDefinitions(before, after); WebPartInfo wi = eObject as WebPartInfo; // If inherited web part load parent properties if (wi.WebPartParentID > 0) { WebPartInfo parentInfo = WebPartInfoProvider.GetWebPartInfo(wi.WebPartParentID); if (parentInfo != null) { webPartProperties = FormHelper.MergeFormDefinitions(parentInfo.WebPartProperties, wi.WebPartProperties); } } else { webPartProperties = wi.WebPartProperties; } break; case "cms.widget": before = PortalFormHelper.LoadProperties("Widget", "Before.xml"); after = PortalFormHelper.LoadProperties("Widget", "After.xml"); defaultSet = FormHelper.CombineFormDefinitions(before, after); defaultValueColumName = "WidgetDefaultValues"; WidgetInfo wii = eObject as WidgetInfo; if (wii != null) { WebPartInfo wiiWp = WebPartInfoProvider.GetWebPartInfo(wii.WidgetWebPartID); if (wiiWp != null) { webPartProperties = FormHelper.MergeFormDefinitions(wiiWp.WebPartProperties, wii.WidgetProperties); } } break; } // Get the web part info if (eObject != null) { String defVal = ValidationHelper.GetString(eObject.GetValue(defaultValueColumName), string.Empty); defaultSet = LoadDefaultValuesXML(defaultSet); fieldEditor.Mode = FieldEditorModeEnum.SystemWebPartProperties; fieldEditor.FormDefinition = FormHelper.MergeFormDefinitions(defaultSet, defVal); fieldEditor.OnAfterDefinitionUpdate += fieldEditor_OnAfterDefinitionUpdate; fieldEditor.OriginalFormDefinition = defaultSet; fieldEditor.WebPartId = eObject.Generalized.ObjectID; } ScriptHelper.HideVerticalTabs(Page); }
/// <summary> /// 增加一条数据 /// </summary> public bool Add(BaseInfo model) { return(dal.Add(model)); }
public virtual void onJoinTableSuccess(Message message) { bg_change_scene.SetActive(true); bg_change_scene.GetComponent <Image>().DOFade(0, 1).OnComplete(FadeFinish); try { resetData(); BaseInfo.gI().isView = false; nUsers = BaseInfo.gI().numberPlayer; for (int i = 0; i < players.Length; i++) { players[i].setExit(); } this.rule = message.reader().ReadByte(); setLuatChoi(rule); masterID = message.reader().ReadUTF(); int len = message.reader().ReadByte(); BaseInfo.gI().timerTurnTable = message.reader().ReadInt(); isPlaying = message.reader().ReadBoolean(); PlayerInfo[] pl = new PlayerInfo[len]; int indexmy = 0; for (int i = 0; i < len; i++) { string name = message.reader().ReadUTF(); string displayname = message.reader().ReadUTF(); string link_avatar = message.reader().ReadUTF(); int idAvata = message.reader().ReadInt(); int isPos = message.reader().ReadByte(); long money = message.reader().ReadLong(); //sbyte genders = message.reader().ReadByte(); bool ready = message.reader().ReadBoolean(); long folowMoney = message.reader().ReadLong(); pl[i] = new PlayerInfo(); pl[i].name = name; pl[i].displayname = displayname; pl[i].idAvata = idAvata; pl[i].link_avatar = link_avatar; pl[i].posServer = isPos; pl[i].money = money; //pl[i].gender = genders; pl[i].folowMoney = folowMoney; if (pl[i].name.Equals(masterID)) { pl[i].isMaster = true; if (pl[i].name.Equals(BaseInfo.gI().mainInfo.nick)) { pl[i].isVisibleInvite = true; } else { pl[i].isVisibleInvite = false; } } else { pl[i].isReady = ready; } if (pl[i].name.Equals(BaseInfo.gI().mainInfo.nick)) { pl[i].isVisibleInvite = false; players[0].CreateInfoPlayer(pl[i]); indexmy = pl[i].posServer; } } for (int i = 1; i < nUsers; i++) { if (!players[i].isSit()) { players[i].setInvite(true); } } for (int i = 0; i < len; i++) { if (i != indexmy) { setPlayerInfo(pl[i], indexmy); } } onJoinTableSuccess(masterID); setTableName(BaseInfo.gI().nameTale, BaseInfo.gI().idTable, BaseInfo.gI().moneyTable); if (!isPlaying && chip_tong != null) { chip_tong.gameObject.SetActive(false); } if (toggleLock != null) { isLock = false; LoadAssetBundle.LoadSprite(toggleLock, Res.AS_UI, "icon_unlock"); } if (BaseInfo.gI().onInfoMe != null) { GameControl.instance.currentCasino.onInfome(BaseInfo.gI().onInfoMe); } //if (chatControl != null) // chatControl.clearList();// vao ban thi clear chat } catch (Exception e) { Debug.LogException(e); } }
public virtual void onJoinView(Message message) { try { resetData(); BaseInfo.gI().isView = true; nUsers = BaseInfo.gI().numberPlayer; for (int i = 0; i < players.Length; i++) { players[i].setExit(); } this.rule = message.reader().ReadByte(); setLuatChoi(rule); masterID = message.reader().ReadUTF(); int len = message.reader().ReadByte(); BaseInfo.gI().timerTurnTable = message.reader().ReadInt(); isPlaying = message.reader().ReadBoolean(); PlayerInfo[] pl = new PlayerInfo[len]; for (int i = 0; i < len; i++) { String name = message.reader().ReadUTF(); String displayname = message.reader().ReadUTF(); String link_avatar = message.reader().ReadUTF(); int idAvata = message.reader().ReadInt(); int isPos = message.reader().ReadByte(); long money = message.reader().ReadLong(); //sbyte genders = message.reader().ReadByte(); bool ready = message.reader().ReadBoolean(); long folowMoney = message.reader().ReadLong(); pl[i] = new PlayerInfo(); pl[i].name = name; pl[i].displayname = displayname; pl[i].idAvata = idAvata; pl[i].link_avatar = link_avatar; pl[i].posServer = isPos; pl[i].money = money; //pl[i].gender = genders; pl[i].folowMoney = folowMoney; if (pl[i].name.Equals(masterID)) { pl[i].isMaster = true; if (pl[i].name.Equals(BaseInfo.gI().mainInfo.nick)) { pl[i].isVisibleInvite = true; } else { pl[i].isVisibleInvite = false; } } else { pl[i].isReady = ready; } players[i].CreateInfoPlayer(pl[i]); } for (int i = 1; i < nUsers; i++) { if (!players[i].isSit()) { players[i].setInvite(true); } } onJoinTableSuccess(masterID); setTableName(BaseInfo.gI().nameTale, BaseInfo.gI().idTable, BaseInfo.gI().moneyTable); } catch (Exception e) { Debug.LogException(e); } }
public virtual void changBetMoney(long betMoney, string info) { setTableName(BaseInfo.gI().nameTale, BaseInfo.gI().idTable, betMoney); PopupAndLoadingScript.instance.popup.ShowPopupTwoButton("", info, delegate { }); }
/// <summary> /// Asynchronously tries to extract metadata for the given <param name="mediaItemAccessor"></param> /// </summary> /// <param name="mediaItemAccessor">Points to the resource for which we try to extract metadata</param> /// <param name="extractedAspectData">Dictionary of <see cref="MediaItemAspect"/>s with the extracted metadata</param> /// <param name="forceQuickMode">If <c>true</c>, nothing is downloaded from the internet</param> /// <returns><c>true</c> if metadata was found and stored into <param name="extractedAspectData"></param>, else <c>false</c></returns> private async Task <bool> TryExtractMovieMetadataAsync(IResourceAccessor mediaItemAccessor, IDictionary <Guid, IList <MediaItemAspect> > extractedAspectData, bool forceQuickMode) { // Get a unique number for this call to TryExtractMetadataAsync. We use this to make reading the debug log easier. // This MetadataExtractor is called in parallel for multiple MediaItems so that the respective debug log entries // for one call are not contained one after another in debug log. We therefore prepend this number before every log entry. var miNumber = Interlocked.Increment(ref _lastMediaItemNumber); bool isStub = extractedAspectData.ContainsKey(StubAspect.ASPECT_ID); try { _debugLogger.Info("[#{0}]: Start extracting metadata for resource '{1}' (forceQuickMode: {2})", miNumber, mediaItemAccessor, forceQuickMode); // This MetadataExtractor only works for MediaItems accessible by an IFileSystemResourceAccessor. // Otherwise it is not possible to find a nfo-file in the MediaItem's directory. if (!(mediaItemAccessor is IFileSystemResourceAccessor)) { _debugLogger.Info("[#{0}]: Cannot extract metadata; mediaItemAccessor is not an IFileSystemResourceAccessor", miNumber); return(false); } // We only extract metadata with this MetadataExtractor, if another MetadataExtractor that was applied before // has identified this MediaItem as a video and therefore added a VideoAspect. if (!extractedAspectData.ContainsKey(VideoAspect.ASPECT_ID)) { _debugLogger.Info("[#{0}]: Cannot extract metadata; this resource is not a video", miNumber); return(false); } // Here we try to find an IFileSystemResourceAccessor pointing to the nfo-file. // If we don't find one, we cannot extract any metadata. IFileSystemResourceAccessor nfoFsra; if (!TryGetNfoSResourceAccessor(miNumber, mediaItemAccessor as IFileSystemResourceAccessor, out nfoFsra)) { return(false); } // Now we (asynchronously) extract the metadata into a stub object. // If there is an error parsing the nfo-file with XmlNfoReader, we at least try to parse for a valid IMDB-ID. // If no metadata was found, nothing can be stored in the MediaItemAspects. NfoMovieReader nfoReader = new NfoMovieReader(_debugLogger, miNumber, false, forceQuickMode, isStub, _httpClient, _settings); using (nfoFsra) { if (!await nfoReader.TryReadMetadataAsync(nfoFsra).ConfigureAwait(false) && !await nfoReader.TryParseForImdbId(nfoFsra).ConfigureAwait(false)) { _debugLogger.Warn("[#{0}]: No valid metadata found", miNumber); return(false); } else if (isStub) { Stubs.MovieStub movie = nfoReader.GetMovieStubs().FirstOrDefault(); if (movie != null) { IList <MultipleMediaItemAspect> providerResourceAspects; if (MediaItemAspect.TryGetAspects(extractedAspectData, ProviderResourceAspect.Metadata, out providerResourceAspects)) { MultipleMediaItemAspect providerResourceAspect = providerResourceAspects.First(pa => pa.GetAttributeValue <int>(ProviderResourceAspect.ATTR_TYPE) == ProviderResourceAspect.TYPE_STUB); string mime = null; if (movie.FileInfo != null && movie.FileInfo.Count > 0) { mime = MimeTypeDetector.GetMimeTypeFromExtension("file" + movie.FileInfo.First().Container); } if (mime != null) { providerResourceAspect.SetAttribute(ProviderResourceAspect.ATTR_MIME_TYPE, mime); } } MediaItemAspect.SetAttribute(extractedAspectData, MediaAspect.ATTR_TITLE, movie.Title); MediaItemAspect.SetAttribute(extractedAspectData, MediaAspect.ATTR_SORT_TITLE, movie.SortTitle != null ? movie.SortTitle : BaseInfo.GetSortTitle(movie.Title)); MediaItemAspect.SetAttribute(extractedAspectData, MediaAspect.ATTR_RECORDINGTIME, movie.Premiered.HasValue ? movie.Premiered.Value : movie.Year.HasValue ? movie.Year.Value : (DateTime?)null); if (movie.FileInfo != null && movie.FileInfo.Count > 0) { extractedAspectData.Remove(VideoStreamAspect.ASPECT_ID); extractedAspectData.Remove(VideoAudioStreamAspect.ASPECT_ID); extractedAspectData.Remove(SubtitleAspect.ASPECT_ID); StubParser.ParseFileInfo(extractedAspectData, movie.FileInfo, movie.Title, movie.Fps); } } } } //Check reimport if (extractedAspectData.ContainsKey(ReimportAspect.ASPECT_ID)) { MovieInfo reimport = new MovieInfo(); reimport.FromMetadata(extractedAspectData); if (!VerifyMovieReimport(nfoReader, reimport)) { ServiceRegistration.Get <ILogger>().Info("NfoMovieMetadataExtractor: Nfo movie metadata from resource '{0}' ignored because it does not match reimport {1}", mediaItemAccessor, reimport); return(false); } } // Then we store the found metadata in the MediaItemAspects. If we only found metadata that is // not (yet) supported by our MediaItemAspects, this MetadataExtractor returns false. if (!nfoReader.TryWriteMetadata(extractedAspectData)) { _debugLogger.Warn("[#{0}]: No metadata was written into MediaItemsAspects", miNumber); return(false); } _debugLogger.Info("[#{0}]: Successfully finished extracting metadata", miNumber); ServiceRegistration.Get <ILogger>().Debug("NfoMovieMetadataExtractor: Assigned nfo movie metadata for resource '{0}'", mediaItemAccessor); return(true); } catch (Exception e) { ServiceRegistration.Get <ILogger>().Warn("NfoMovieMetadataExtractor: Exception while extracting metadata for resource '{0}'; enable debug logging for more details.", mediaItemAccessor); _debugLogger.Error("[#{0}]: Exception while extracting metadata", e, miNumber); return(false); } }
public void onClickGame(string obj) { PanelWaiting.instance.ShowLoading(); SoundManager.instance.startClickButtonAudio(); switch (obj) { case "Button_Phom": BaseInfo.gI().gameID = GameID.PHOM; break; case "Button_TLMN": BaseInfo.gI().gameID = GameID.TLMN; break; case "Button_XiTo": BaseInfo.gI().gameID = GameID.XITO; break; case "Button_MB": BaseInfo.gI().gameID = GameID.MAUBINH; break; case "Button_Poker": BaseInfo.gI().gameID = GameID.POKER; break; case "Button_Sam": BaseInfo.gI().gameID = GameID.XAM; break; case "Button_3Cay": BaseInfo.gI().gameID = GameID.BACAY; break; case "Button_Lieng": BaseInfo.gI().gameID = GameID.LIENG; break; case "Button_XocDia": BaseInfo.gI().gameID = GameID.XOCDIA; break; case "Button_TaiXiu": BaseInfo.gI().gameID = GameID.TAIXIU; //sua //gameControl.setCasino(GameID.TAIXIU, BaseInfo.gI().typetableLogin); //SendData.onjoinTaiXiu((byte)BaseInfo.gI().typetableLogin); //gameControl.top.setGameName(); return; case "Button_TLMNSl": BaseInfo.gI().gameID = GameID.TLMNsolo; break; case "Button_Xeng": BaseInfo.gI().gameID = GameID.XENG; //SendData.onJoinXengHoaQua(); //gameControl.top.setGameName(); return; } //gameControl.top.setGameName(); SendData.onSendGameID((sbyte)BaseInfo.gI().gameID); }
public void clickAnBanFull(bool isChecked) { PanelWaiting.instance.ShowLoading(); BaseInfo.gI().isHideTabeFull = isChecked; SendData.onUpdateRoom(); }
/// <summary> /// 更新一条数据 /// </summary> public bool Update(BaseInfo model) { return(dal.Update(model)); }
private void ParseObject() { var info = new BaseInfo(); parser.ReadLine(); info.Name = parser.ReadLine(); parser.ReadLine(); info.AssetName = parser.ReadLine(); parser.ReadLine(); info.Translation = parser.ReadVector3(); // Translation vector of base Transform parser.ReadLine(); info.Rotation = parser.ReadVector3(); // Euler angles of base Transform parser.ReadLine(); info.AssetName = info.AssetName.Replace('\\', '/'); builder.BeginEntity(info.Name); Log.WriteLine(LogLevel.Info, "Parsing {0}...", info.Name); var posCount = parser.ReadInt(); if (posCount > 0) { // add nodes as separate entities. var sb = new StringBuilder(); for (int i = 0; i < posCount; i++) { var nodeName = info.Name + ".node" + i; if (sb.Length != 0) sb.Append(";"); sb.Append(nodeName); ParseNode(nodeName, i == 0); } builder.BeginComponent("WaypointComponent"); builder.AddParameter("nodes", sb.ToString()); builder.EndComponent(); } var fn = Path.GetFileNameWithoutExtension(info.AssetName); builder.AddAsset(fn + ".mesh", info.AssetName.EndsWith(".obj"), info.AssetName); builder.BeginComponent("RenderComponent"); builder.AddParameter("meshData", fn + ".mesh"); builder.EndComponent(); parser.ReadLine(); var type = parser.ReadLine(); if (info.AssetName.EndsWith(".smd") && type != ObjectType.Actor) { // it's probably an animated object, check for idle animation var anim = Directory.GetFiles(baseDir + Path.GetDirectoryName(info.AssetName), "anims/*.smd", SearchOption.AllDirectories).FirstOrDefault(); if (anim != null) { builder.AddAsset(fn + ".rest", false, info.AssetName); builder.AddAsset(fn + ".animation", false, anim.Remove(0, baseDir.Length).Replace('\\', '/')); builder.BeginComponent("SimpleAnimationController"); builder.AddParameter("animData", fn + ".animation"); builder.AddParameter("restPose", fn + ".rest"); builder.EndComponent(); } } switch (type) { case ObjectType.Actor: ParseActor(info); break; case ObjectType.Static: ParseProp(info); break; case ObjectType.Projectile: ParseProjectile(); break; case ObjectType.Particles: ParseParticles(); break; case ObjectType.Sensor: ParseSensor(); break; case ObjectType.PushingBox: ParsePushableBox(); break; case ObjectType.MovingBox: ParseMovableBox(); break; default: Log.WriteLine(LogLevel.Fatal, "unknown LSA object type: " + type); break; } parser.ReadLine();// #script_filename_whatever var scriptName = parser.ReadLine(); parser.ReadLine(); // #script_length var len = parser.ReadInt(); parser.ReadLine(); string source = ""; if (scriptName != "none") { builder.BeginComponent("LuaComponent"); builder.AddParameter("sourceRef", Path.Combine(baseDir, scriptName)); builder.EndComponent(); } else if (len != 0) { var s = new StringBuilder(); while (s.Length < len) s.Append(parser.ReadLine() + "\n"); source = s.ToString(); builder.BeginComponent("LuaComponent"); builder.AddParameter("source", source); builder.EndComponent(); } if (source.Length <= len) parser.ReadLine(); builder.EndEntity(); }
public void sendChatQuick() { SendData.onSendMsgChat(BaseInfo.gI().mainInfo.nick, "hahaha"); }
public bool TryExtractRelationships(IDictionary <Guid, IList <MediaItemAspect> > aspects, bool importOnly, out IList <RelationshipItem> extractedLinkedAspects) { extractedLinkedAspects = null; if (!MovieMetadataExtractor.IncludeActorDetails) { return(false); } if (importOnly) { return(false); } if (BaseInfo.IsVirtualResource(aspects)) { return(false); } MovieInfo movieInfo = new MovieInfo(); if (!movieInfo.FromMetadata(aspects)) { return(false); } if (CheckCacheContains(movieInfo)) { return(false); } int count = 0; if (!MovieMetadataExtractor.SkipOnlineSearches) { OnlineMatcherService.Instance.UpdatePersons(movieInfo, PersonAspect.OCCUPATION_ACTOR, importOnly); count = movieInfo.Actors.Where(p => p.HasExternalId).Count(); if (!movieInfo.IsRefreshed) { movieInfo.HasChanged = true; //Force save to update external Ids for metadata found by other MDEs } } else { count = movieInfo.Actors.Where(p => !string.IsNullOrEmpty(p.Name)).Count(); } if (movieInfo.Actors.Count == 0) { return(false); } if (BaseInfo.CountRelationships(aspects, LinkedRole) < count || (BaseInfo.CountRelationships(aspects, LinkedRole) == 0 && movieInfo.Actors.Count > 0)) { movieInfo.HasChanged = true; //Force save if no relationship exists } if (!movieInfo.HasChanged) { return(false); } AddToCheckCache(movieInfo); extractedLinkedAspects = new List <RelationshipItem>(); foreach (PersonInfo person in movieInfo.Actors) { person.AssignNameId(); person.HasChanged = movieInfo.HasChanged; IDictionary <Guid, IList <MediaItemAspect> > personAspects = new Dictionary <Guid, IList <MediaItemAspect> >(); person.SetMetadata(personAspects); if (personAspects.ContainsKey(ExternalIdentifierAspect.ASPECT_ID)) { Guid existingId; if (TryGetIdFromCache(person, out existingId)) { extractedLinkedAspects.Add(new RelationshipItem(personAspects, existingId)); } else { extractedLinkedAspects.Add(new RelationshipItem(personAspects, Guid.Empty)); } } } return(extractedLinkedAspects.Count > 0); }
private static IEnumerable<DataColumn> ExtractDataColumns(BaseInfo info) { var type = info.GetType(); return from c in info.ColumnNames let prop = type.GetProperty(c) where prop != null select new DataColumn(c, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType); }
public override void onInfome(Message message) { base.onInfome(message); try { isStart = true; players[0].setPlaying(true); if (posbx == 0 && !timer_baoxam.isActive()) { timer_baoxam.gameObject.transform.localPosition = players[0].gameObject.transform.localPosition; } disableAllBtnTable(); int sizeCardHand = message.reader().ReadByte(); int[] cardHand = new int[sizeCardHand]; for (int i = 0; i < sizeCardHand; i++) { cardHand[i] = message.reader().ReadByte(); } players[0].setCardHand(cardHand, false, false, false); int sizeCardFire = message.reader().ReadByte(); if (sizeCardFire > 0) { int[] cardFire = new int[sizeCardFire]; for (int i = 0; i < sizeCardFire; i++) { cardFire[i] = message.reader().ReadByte(); } tableArrCard = cardFire; tableArrCard2.setArrCard(cardFire); } string turnName = message.reader().ReadUTF(); int turnTime = message.reader().ReadInt(); setTurn(turnName, turnTime); if (turnName.ToLower().Equals( BaseInfo.gI().mainInfo.nick.ToLower())) { btn_danhbai.gameObject.SetActive(true); if (tableArrCard != null) { if (tableArrCard.Length > 0) { btn_boluot.gameObject.SetActive(true); } else { btn_boluot.gameObject.SetActive(false); } } else { btn_boluot.gameObject.SetActive(false); } } else { btn_danhbai.gameObject.SetActive(false); btn_boluot.gameObject.SetActive(false); } } catch (Exception e) { } }
protected async Task ExtractAlbumAndArtistFanArt(Guid mediaItemId, IDictionary <Guid, IList <MediaItemAspect> > aspects) { if (BaseInfo.IsVirtualResource(aspects)) { return; } IResourceLocator mediaItemLocator = GetResourceLocator(aspects); if (mediaItemLocator == null) { return; } //Whether local fanart should be stored in the fanart cache bool shouldCacheLocal = ShouldCacheLocalFanArt(mediaItemLocator.NativeResourcePath, AudioMetadataExtractor.CacheLocalFanArt, AudioMetadataExtractor.CacheOfflineFanArt); if (!shouldCacheLocal && AudioMetadataExtractor.SkipFanArtDownload) { return; //Nothing to do } TrackInfo trackInfo = new TrackInfo(); trackInfo.FromMetadata(aspects); AlbumInfo albumInfo = trackInfo.CloneBasicInstance <AlbumInfo>(); string albumTitle = albumInfo.ToString(); var albumDirectory = ResourcePathHelper.Combine(mediaItemLocator.NativeResourcePath, "../"); if (AudioMetadataExtractor.IsDiscFolder(albumTitle, albumDirectory.FileName)) { //Probably a CD folder so try next parent albumDirectory = ResourcePathHelper.Combine(albumDirectory, "../"); } //Artist fanart may be stored in the album directory, so get the artists now IList <Tuple <Guid, string> > artists = GetArtists(aspects); //Album fanart if (RelationshipExtractorUtils.TryGetLinkedId(AudioAlbumAspect.ROLE_ALBUM, aspects, out Guid albumMediaItemId) && AddToCache(albumMediaItemId)) { //If the track is not a stub, Store track tag images in the album if (!aspects.ContainsKey(ReimportAspect.ASPECT_ID) && MediaItemAspect.TryGetAttribute(aspects, MediaAspect.ATTR_ISSTUB, out bool isStub) && isStub == false) { await ExtractTagFanArt(mediaItemLocator, albumMediaItemId, albumTitle); } if (shouldCacheLocal) { await ExtractAlbumFolderFanArt(mediaItemLocator.NativeSystemId, albumDirectory, albumMediaItemId, albumTitle, artists).ConfigureAwait(false); } if (!AudioMetadataExtractor.SkipFanArtDownload) { await OnlineMatcherService.Instance.DownloadAudioFanArtAsync(albumMediaItemId, albumInfo).ConfigureAwait(false); } } if (artists != null) { await ExtractArtistFolderFanArt(mediaItemLocator.NativeSystemId, albumDirectory, artists).ConfigureAwait(false); } }
private async Task <bool> TryExtractStubItemsAsync(IResourceAccessor mediaItemAccessor, ICollection <IDictionary <Guid, IList <MediaItemAspect> > > extractedStubAspectData) { // Get a unique number for this call to TryExtractMetadataAsync. We use this to make reading the debug log easier. // This MetadataExtractor is called in parallel for multiple MediaItems so that the respective debug log entries // for one call are not contained one after another in debug log. We therefore prepend this number before every log entry. var miNumber = Interlocked.Increment(ref _lastMediaItemNumber); try { _debugLogger.Info("[#{0}]: Start extracting stubs for resource '{1}'", miNumber, mediaItemAccessor); if (!IsStubResource(mediaItemAccessor)) { _debugLogger.Info("[#{0}]: Cannot extract stubs; file does not have a supported extension", miNumber); return(false); } // This MetadataExtractor only works for MediaItems accessible by an IFileSystemResourceAccessor. // Otherwise it is not possible to find a stub-file in the MediaItem's directory. if (!(mediaItemAccessor is IFileSystemResourceAccessor)) { _debugLogger.Info("[#{0}]: Cannot extract stubs; mediaItemAccessor is not an IFileSystemResourceAccessor", miNumber); return(false); } var fsra = mediaItemAccessor as IFileSystemResourceAccessor; var albumStubReader = new StubAlbumReader(_debugLogger, miNumber, true, _settings); if (fsra != null && await albumStubReader.TryReadMetadataAsync(fsra).ConfigureAwait(false)) { AlbumStub album = albumStubReader.GetAlbumStubs().FirstOrDefault(); if (album != null && album.Tracks != null && album.Tracks > 0) { for (int trackNo = 1; trackNo <= album.Tracks.Value; trackNo++) { Dictionary <Guid, IList <MediaItemAspect> > extractedAspectData = new Dictionary <Guid, IList <MediaItemAspect> >(); string title = string.Format("{0}: {1}", album.Title, "Track " + trackNo); MultipleMediaItemAspect providerResourceAspect = MediaItemAspect.CreateAspect(extractedAspectData, ProviderResourceAspect.Metadata); providerResourceAspect.SetAttribute(ProviderResourceAspect.ATTR_RESOURCE_INDEX, 0); providerResourceAspect.SetAttribute(ProviderResourceAspect.ATTR_TYPE, ProviderResourceAspect.TYPE_STUB); providerResourceAspect.SetAttribute(ProviderResourceAspect.ATTR_RESOURCE_ACCESSOR_PATH, fsra.CanonicalLocalResourcePath.Serialize()); providerResourceAspect.SetAttribute(ProviderResourceAspect.ATTR_MIME_TYPE, "audio/L16"); SingleMediaItemAspect audioAspect = MediaItemAspect.GetOrCreateAspect(extractedAspectData, AudioAspect.Metadata); audioAspect.SetAttribute(AudioAspect.ATTR_ISCD, true); audioAspect.SetAttribute(AudioAspect.ATTR_TRACK, trackNo); audioAspect.SetAttribute(AudioAspect.ATTR_TRACKNAME, title); audioAspect.SetAttribute(AudioAspect.ATTR_ENCODING, "PCM"); if (album.Cd.HasValue) { audioAspect.SetAttribute(AudioAspect.ATTR_DISCID, album.Cd.Value); } audioAspect.SetAttribute(AudioAspect.ATTR_BITRATE, 1411); // 44.1 kHz * 16 bit * 2 channel audioAspect.SetAttribute(AudioAspect.ATTR_CHANNELS, 2); audioAspect.SetAttribute(AudioAspect.ATTR_NUMTRACKS, album.Tracks.Value); audioAspect.SetAttribute(AudioAspect.ATTR_ALBUM, album.Title); if (album.Artists.Count > 0) { audioAspect.SetCollectionAttribute(AudioAspect.ATTR_ALBUMARTISTS, album.Artists); } SingleMediaItemAspect stubAspect = MediaItemAspect.GetOrCreateAspect(extractedAspectData, StubAspect.Metadata); stubAspect.SetAttribute(StubAspect.ATTR_DISC_NAME, album.DiscName); stubAspect.SetAttribute(StubAspect.ATTR_MESSAGE, album.Message); MediaItemAspect.SetAttribute(extractedAspectData, MediaAspect.ATTR_TITLE, title); MediaItemAspect.SetAttribute(extractedAspectData, MediaAspect.ATTR_SORT_TITLE, BaseInfo.GetSortTitle(title)); MediaItemAspect.SetAttribute(extractedAspectData, MediaAspect.ATTR_ISVIRTUAL, false); MediaItemAspect.SetAttribute(extractedAspectData, MediaAspect.ATTR_ISSTUB, true); MediaItemAspect.SetAttribute(extractedAspectData, MediaAspect.ATTR_RECORDINGTIME, fsra.LastChanged); extractedStubAspectData.Add(extractedAspectData); } } } else { _debugLogger.Warn("[#{0}]: No valid metadata found in album stub file", miNumber); } _debugLogger.Info("[#{0}]: Successfully finished extracting stubs", miNumber); return(true); } catch (Exception e) { ServiceRegistration.Get <ILogger>().Warn("StubAudioMetadataExtractor: Exception while extracting stubs for resource '{0}'; enable debug logging for more details.", mediaItemAccessor); _debugLogger.Error("[#{0}]: Exception while extracting stubs", e, miNumber); return(false); } }
private object ExecuteGetCity(BaseInfo baseinfo) { if (baseinfo != null) { a = baseinfo; City = new DataItem().CityItem(baseinfo.Name); } return null; }
public void onClickCancelAll() { GameControl.instance.sound.startClickButtonAudio(); BaseInfo.gI().isNhanLoiMoiChoi = false; onHide(); }
public virtual bool TryExtractMetadata(IResourceAccessor mediaItemAccessor, IDictionary <Guid, IList <MediaItemAspect> > extractedAspectData, bool importOnly, bool forceQuickMode) { IFileSystemResourceAccessor fsra = mediaItemAccessor as IFileSystemResourceAccessor; if (fsra == null) { return(false); } if (!fsra.IsFile) { return(false); } string fileName = fsra.ResourceName; if (!HasAudioExtension(fileName)) { return(false); } bool refresh = false; if (extractedAspectData.ContainsKey(AudioAspect.ASPECT_ID)) { refresh = true; } try { TrackInfo trackInfo = new TrackInfo(); if (refresh) { trackInfo.FromMetadata(extractedAspectData); } if (!trackInfo.IsBaseInfoPresent) { File tag = null; try { ByteVector.UseBrokenLatin1Behavior = true; // Otherwise we have problems retrieving non-latin1 chars tag = File.Create(new ResourceProviderFileAbstraction(fsra)); } catch (CorruptFileException) { // Only log at the info level here - And simply return false. This makes the importer know that we // couldn't perform our task here. ServiceRegistration.Get <ILogger>().Info("AudioMetadataExtractor: Audio file '{0}' seems to be broken", fsra.CanonicalLocalResourcePath); return(false); } using (tag) { // Some file extensions like .mp4 can contain audio and video. Do not handle files with video content here. if (tag.Properties.VideoHeight > 0 && tag.Properties.VideoWidth > 0) { return(false); } fileName = ProviderPathHelper.GetFileNameWithoutExtension(fileName) ?? string.Empty; string title; string sortTitle; string artist; uint? trackNo; GuessMetadataFromFileName(fileName, out title, out artist, out trackNo); if (!string.IsNullOrEmpty(title)) { title = CultureInfo.InvariantCulture.TextInfo.ToTitleCase(title.ToLowerInvariant()); } if (!string.IsNullOrEmpty(artist)) { artist = CultureInfo.InvariantCulture.TextInfo.ToTitleCase(artist.ToLowerInvariant()); } if (!string.IsNullOrEmpty(tag.Tag.Title)) { title = tag.Tag.Title.Trim(); } sortTitle = BaseInfo.GetSortTitle(title); if (!string.IsNullOrEmpty(tag.Tag.TitleSort)) { sortTitle = tag.Tag.TitleSort.Trim(); } IEnumerable <string> artists; if (tag.Tag.Performers.Length > 0) { artists = tag.Tag.Performers; if ((tag.TagTypes & TagTypes.Id3v2) != 0) { artists = PatchID3v23Enumeration(artists); } } else { artists = artist == null ? null : new string[] { artist.Trim() } }; if (tag.Tag.Track != 0) { trackNo = tag.Tag.Track; } if (importOnly) { MultipleMediaItemAspect providerResourceAspect = MediaItemAspect.CreateAspect(extractedAspectData, ProviderResourceAspect.Metadata); providerResourceAspect.SetAttribute(ProviderResourceAspect.ATTR_RESOURCE_INDEX, 0); providerResourceAspect.SetAttribute(ProviderResourceAspect.ATTR_PRIMARY, true); providerResourceAspect.SetAttribute(ProviderResourceAspect.ATTR_SIZE, fsra.Size); providerResourceAspect.SetAttribute(ProviderResourceAspect.ATTR_RESOURCE_ACCESSOR_PATH, fsra.CanonicalLocalResourcePath.Serialize()); // FIXME Albert: tag.MimeType returns taglib/mp3 for an MP3 file. This is not what we want and collides with the // mimetype handling in the BASS player, which expects audio/xxx. if (!string.IsNullOrWhiteSpace(tag.MimeType)) { providerResourceAspect.SetAttribute(ProviderResourceAspect.ATTR_MIME_TYPE, tag.MimeType.Replace("taglib/", "audio/")); } MediaItemAspect.SetAttribute(extractedAspectData, MediaAspect.ATTR_TITLE, title); MediaItemAspect.SetAttribute(extractedAspectData, MediaAspect.ATTR_SORT_TITLE, sortTitle); MediaItemAspect.SetAttribute(extractedAspectData, MediaAspect.ATTR_ISVIRTUAL, false); MediaItemAspect.SetAttribute(extractedAspectData, MediaAspect.ATTR_COMMENT, StringUtils.TrimToNull(tag.Tag.Comment)); MediaItemAspect.SetAttribute(extractedAspectData, MediaAspect.ATTR_RECORDINGTIME, fsra.LastChanged); } trackInfo.TrackName = title; trackInfo.TrackNameSort = sortTitle; if (tag.Properties.Codecs.Count() > 0) { trackInfo.Encoding = tag.Properties.Codecs.First().Description; } if (tag.Properties.Duration.TotalSeconds != 0) { trackInfo.Duration = (long)tag.Properties.Duration.TotalSeconds; } if (tag.Properties.AudioBitrate != 0) { trackInfo.BitRate = (int)tag.Properties.AudioBitrate; } if (tag.Properties.AudioChannels != 0) { trackInfo.Channels = (int)tag.Properties.AudioChannels; } if (tag.Properties.AudioSampleRate != 0) { trackInfo.SampleRate = (int)tag.Properties.AudioSampleRate; } TagLib.Id3v2.Tag id3Tag = (TagLib.Id3v2.Tag)tag.GetTag(TagTypes.Id3v2, false); if (id3Tag != null && !id3Tag.IsEmpty) { trackInfo.Compilation = id3Tag.IsCompilation; } trackInfo.Album = !string.IsNullOrEmpty(tag.Tag.Album) ? tag.Tag.Album.Trim() : null; if (!string.IsNullOrEmpty(tag.Tag.AlbumSort)) { IAudioRelationshipExtractor.StoreAlbum(extractedAspectData, tag.Tag.Album, tag.Tag.AlbumSort.Trim()); } if (trackNo.HasValue) { trackInfo.TrackNum = (int)trackNo.Value; } if (tag.Tag.TrackCount != 0) { trackInfo.TotalTracks = (int)tag.Tag.TrackCount; } if (tag.Tag.Disc != 0) { trackInfo.DiscNum = (int)tag.Tag.Disc; } if (tag.Tag.DiscCount != 0) { trackInfo.TotalDiscs = (int)tag.Tag.DiscCount; } if (!string.IsNullOrEmpty(tag.Tag.Lyrics)) { trackInfo.TrackLyrics = tag.Tag.Lyrics; } if (tag.Tag.TrackCount != 0) { trackInfo.TotalTracks = (int)tag.Tag.TrackCount; } if (!string.IsNullOrEmpty(tag.Tag.MusicBrainzTrackId)) { trackInfo.MusicBrainzId = tag.Tag.MusicBrainzTrackId; } if (!string.IsNullOrEmpty(tag.Tag.MusicBrainzReleaseId)) { trackInfo.AlbumMusicBrainzId = tag.Tag.MusicBrainzReleaseId; } if (!string.IsNullOrEmpty(tag.Tag.MusicBrainzDiscId)) { trackInfo.AlbumMusicBrainzDiscId = tag.Tag.MusicBrainzDiscId; } if (!string.IsNullOrEmpty(tag.Tag.AmazonId)) { trackInfo.AlbumAmazonId = tag.Tag.AmazonId; } if (!string.IsNullOrEmpty(tag.Tag.MusicIpId)) { trackInfo.MusicIpId = tag.Tag.MusicIpId; } trackInfo.Artists = new List <PersonInfo>(); if (artists != null) { foreach (string artistName in ApplyAdditionalSeparator(artists)) { trackInfo.Artists.Add(new PersonInfo() { Name = artistName.Trim(), Occupation = PersonAspect.OCCUPATION_ARTIST, ParentMediaName = trackInfo.Album, MediaName = trackInfo.TrackName }); } } //Save id if possible if (trackInfo.Artists.Count == 1 && !string.IsNullOrEmpty(tag.Tag.MusicBrainzArtistId)) { trackInfo.Artists[0].MusicBrainzId = tag.Tag.MusicBrainzArtistId; } IEnumerable <string> albumArtists = tag.Tag.AlbumArtists; if ((tag.TagTypes & TagTypes.Id3v2) != 0) { albumArtists = PatchID3v23Enumeration(albumArtists); } trackInfo.AlbumArtists = new List <PersonInfo>(); if (albumArtists != null) { foreach (string artistName in ApplyAdditionalSeparator(albumArtists)) { trackInfo.AlbumArtists.Add(new PersonInfo() { Name = artistName.Trim(), Occupation = PersonAspect.OCCUPATION_ARTIST, ParentMediaName = trackInfo.Album, MediaName = trackInfo.TrackName }); } } //Save id if possible if (trackInfo.AlbumArtists.Count == 1 && !string.IsNullOrEmpty(tag.Tag.MusicBrainzReleaseArtistId)) { trackInfo.AlbumArtists[0].MusicBrainzId = tag.Tag.MusicBrainzReleaseArtistId; } IEnumerable <string> composers = tag.Tag.Composers; if ((tag.TagTypes & TagTypes.Id3v2) != 0) { composers = PatchID3v23Enumeration(composers); } trackInfo.Composers = new List <PersonInfo>(); if (composers != null) { foreach (string composerName in ApplyAdditionalSeparator(composers)) { trackInfo.Composers.Add(new PersonInfo() { Name = composerName.Trim(), Occupation = PersonAspect.OCCUPATION_COMPOSER, ParentMediaName = trackInfo.Album, MediaName = trackInfo.TrackName }); } } if (tag.Tag.Genres.Length > 0) { IEnumerable <string> genres = tag.Tag.Genres; if ((tag.TagTypes & TagTypes.Id3v2) != 0) { genres = PatchID3v23Enumeration(genres); } trackInfo.Genres = ApplyAdditionalSeparator(genres).Select(s => new GenreInfo { Name = s.Trim() }).ToList(); OnlineMatcherService.Instance.AssignMissingMusicGenreIds(trackInfo.Genres); } int year = (int)tag.Tag.Year; if (year >= 30 && year <= 99) { year += 1900; } if (year >= 1930 && year <= 2030) { trackInfo.ReleaseDate = new DateTime(year, 1, 1); } if (!trackInfo.HasThumbnail) { // The following code gets cover art images from file (embedded) or from windows explorer cache (supports folder.jpg). IPicture[] pics = tag.Tag.Pictures; if (pics.Length > 0) { try { using (MemoryStream stream = new MemoryStream(pics[0].Data.Data)) { trackInfo.Thumbnail = stream.ToArray(); trackInfo.HasChanged = true; } } // Decoding of invalid image data can fail, but main MediaItem is correct. catch { } } else { // In quick mode only allow thumbs taken from cache. bool cachedOnly = importOnly || forceQuickMode; // Thumbnail extraction fileName = mediaItemAccessor.ResourcePathName; IThumbnailGenerator generator = ServiceRegistration.Get <IThumbnailGenerator>(); byte[] thumbData; ImageType imageType; if (generator.GetThumbnail(fileName, cachedOnly, out thumbData, out imageType)) { trackInfo.Thumbnail = thumbData; trackInfo.HasChanged = true; } } } } if (string.IsNullOrEmpty(trackInfo.Album) || trackInfo.Artists.Count == 0) { MusicNameMatcher.MatchTrack(fileName, trackInfo); } } //Determine compilation if (importOnly && !trackInfo.Compilation) { if (trackInfo.AlbumArtists.Count > 0 && (trackInfo.AlbumArtists[0].Name.IndexOf("Various", StringComparison.InvariantCultureIgnoreCase) >= 0 || trackInfo.AlbumArtists[0].Name.Equals("VA", StringComparison.InvariantCultureIgnoreCase))) { trackInfo.Compilation = true; } else { //Look for itunes compilation folder var mediaItemPath = mediaItemAccessor.CanonicalLocalResourcePath; var albumMediaItemDirectoryPath = ResourcePathHelper.Combine(mediaItemPath, "../"); var artistMediaItemDirectoryPath = ResourcePathHelper.Combine(mediaItemPath, "../../"); if (albumMediaItemDirectoryPath.FileName != null && IsDiscFolder(trackInfo.Album, albumMediaItemDirectoryPath.FileName)) { //Probably a CD folder so try next parent artistMediaItemDirectoryPath = ResourcePathHelper.Combine(mediaItemPath, "../../../"); } if (artistMediaItemDirectoryPath.FileName != null && artistMediaItemDirectoryPath.FileName.IndexOf("Compilation", StringComparison.InvariantCultureIgnoreCase) >= 0) { trackInfo.Compilation = true; } } } if (!refresh) { //Check artists trackInfo.Artists = GetCorrectedArtistsList(trackInfo, trackInfo.Artists); trackInfo.AlbumArtists = GetCorrectedArtistsList(trackInfo, trackInfo.AlbumArtists); } trackInfo.AssignNameId(); if (!forceQuickMode) { AudioCDMatcher.GetDiscMatchAndUpdate(mediaItemAccessor.ResourcePathName, trackInfo); if (SkipOnlineSearches && !SkipFanArtDownload) { TrackInfo tempInfo = trackInfo.Clone(); OnlineMatcherService.Instance.FindAndUpdateTrack(tempInfo, importOnly); trackInfo.CopyIdsFrom(tempInfo); trackInfo.HasChanged = tempInfo.HasChanged; } else if (!SkipOnlineSearches) { OnlineMatcherService.Instance.FindAndUpdateTrack(trackInfo, importOnly); } } if (refresh) { if ((IncludeArtistDetails && !BaseInfo.HasRelationship(extractedAspectData, PersonAspect.ROLE_ARTIST) && trackInfo.Artists.Count > 0) || (IncludeArtistDetails && !BaseInfo.HasRelationship(extractedAspectData, PersonAspect.ROLE_ALBUMARTIST) && trackInfo.AlbumArtists.Count > 0) || (IncludeComposerDetails && !BaseInfo.HasRelationship(extractedAspectData, PersonAspect.ROLE_COMPOSER) && trackInfo.Composers.Count > 0)) { trackInfo.HasChanged = true; } } if (!trackInfo.HasChanged && !importOnly) { return(false); } trackInfo.SetMetadata(extractedAspectData); if (importOnly && !forceQuickMode) { //Store metadata for the Relationship Extractors if (IncludeArtistDetails) { IAudioRelationshipExtractor.StorePersons(extractedAspectData, trackInfo.Artists, false); IAudioRelationshipExtractor.StorePersons(extractedAspectData, trackInfo.AlbumArtists, true); } if (IncludeComposerDetails) { IAudioRelationshipExtractor.StorePersons(extractedAspectData, trackInfo.Composers, false); } } return(trackInfo.IsBaseInfoPresent); } catch (UnsupportedFormatException) { ServiceRegistration.Get <ILogger>().Info("AudioMetadataExtractor: Unsupported audio file '{0}'", fsra.CanonicalLocalResourcePath); return(false); } catch (Exception e) { // Only log at the info level here - And simply return false. This makes the importer know that we // couldn't perform our task here ServiceRegistration.Get <ILogger>().Info("AudioMetadataExtractor: Exception reading resource '{0}' (Text: '{1}')", fsra.CanonicalLocalResourcePath, e.Message); } return(false); }
/// <summary> /// Selects base info item /// </summary> /// <param name="bi">Base info item definition</param> private String SelectItem(BaseInfo bi) { String script = String.Empty; int parentID = ValidationHelper.GetInteger(bi.GetValue(itemParentColumn), 0); BaseInfo biParent = BaseAbstractInfoProvider.GetInfoById(categoryObjectType, parentID); if (biParent != null) { String categoryPath = ValidationHelper.GetString(biParent.GetValue(categoryPathColumn), String.Empty); string path = categoryPath + "/" + bi.Generalized.ObjectCodeName; script += SelectAfterLoad(path, bi.Generalized.ObjectID, "item", parentID, true, true); } return script; }
public void Update() { if (timer != null) { if (isTurns && getName().Length != 0) { if (!timer.gameObject.activeInHierarchy) { timer.gameObject.SetActive(true); } dura += Time.deltaTime; if (dura < BaseInfo.gI().timerTurnTable) { float percent; if (casinoStage.timeReceiveTurn == 0) { percent = 1; } else { percent = dura * 100 / casinoStage.timeReceiveTurn; } float temp = 100f - percent; /*if (temp > 75) { * //if (pos == 0 && casinoStage.isStart && isOne && !BaseInfo.gI().isView) { * // GameControl.instance.sound.startCountDownAudio(); * // isOne = false; * //} * if (pos == 0 && !BaseInfo.gI().isView) { * GameControl.instance.sound.pauseSound(); * } * timer.sprite.color = Color.green; * * } else*/ if (temp > 50) { if (pos == 0 && !BaseInfo.gI().isView) { GameControl.instance.sound.pauseSound(); } timer.sprite.color = Color.green; } else if (temp > 25) { if (pos == 0 && !BaseInfo.gI().isView) { GameControl.instance.sound.pauseSound(); } timer.sprite.color = Color.yellow; } else { //if (pos == 0 && !BaseInfo.gI().isView) { // GameControl.instance.sound.pauseSound(); //} if (pos == 0 && isOne && !BaseInfo.gI().isView) { GameControl.instance.sound.startCountDownAudio(); isOne = false; } timer.sprite.color = Color.red; } timer.setPercentage(percent); } if (dura >= BaseInfo.gI().timerTurnTable) { if (pos == 0 && !BaseInfo.gI().isView) { GameControl.instance.sound.pauseSound(); } } } else if (timer.gameObject.activeInHierarchy) { dura = 0; // loop if (pos == 0 && !BaseInfo.gI().isView) { GameControl.instance.sound.pauseSound(); } timer.gameObject.SetActive(false); } //if (www != null) { // if (www.isDone && !isOne) { // raw_avatar.texture = www.texture; // isOneAvata = true; // } //} } }
protected override void OnInit(EventArgs e) { if (StopProcessing) { // No actions if processing is stopped } else { if (!String.IsNullOrEmpty(AfterDeleteScript)) { gridElem.OnAction += gridElem_OnAction; } // If edit element name is set, load it directly. Otherwise load first element with prefix 'edit' in it's name. uiEdit = String.IsNullOrEmpty(EditElement) ? UIContext.UIElement.GetEditElement() : UIElementInfoProvider.GetUIElementInfo(UIContext.UIElement.ElementResourceID, EditElement); gridElem.CurrentResolver.SetNamedSourceData("UIContext", UIContext); if (uiEdit != null) { UIContextData data = new UIContextData(); data.LoadData(uiEdit.ElementProperties); editInDialog = data["OpenInDialog"].ToBoolean(false); gridElem.EditInDialog = editInDialog; gridElem.DialogWidth = data["DialogWidth"].ToString(null); gridElem.DialogHeight = data["DialogHeight"].ToString(null); } // Check modify permission on object type, to disable delete button var objectType = ObjectType; // Pass element's object type to unigrid. It may be overridden with unigrid definition if (!String.IsNullOrEmpty(objectType)) { gridElem.ObjectType = objectType; } mEmptyCurrentInfo = gridElem.InfoObject; // Try to fake siteID (if object has siteID column) if ((mEmptyCurrentInfo != null) && (mEmptyCurrentInfo.TypeInfo.SiteIDColumn != ObjectTypeInfo.COLUMN_NAME_UNKNOWN)) { mEmptyCurrentInfo.Generalized.ObjectSiteID = GetSiteID(mEmptyCurrentInfo); } // Apply delete check only for non global admins if (!MembershipContext.AuthenticatedUser.IsGlobalAdministrator) { gridElem.OnBeforeDataReload += gridElem_OnBeforeDataReload; gridElem.OnExternalDataBound += gridElem_OnExternalDataBound; } // Must be called before permission check to initialize grid extenders properly base.OnInit(e); if (CheckInfoViewPermissions) { // Check view permission for object type if (!CheckViewPermissions(mEmptyCurrentInfo)) { gridElem.StopProcessing = true; gridElem.Visible = false; } } } }
public bool SendPhoneBaidu(BaseInfo baseInfo) { PhoneGCMInfo info = (PhoneGCMInfo)baseInfo; JSONInfo Info1 = new JSONInfo(); subJSONInfo Info2 = new subJSONInfo(); JSONResult Info3 = new JSONResult(); ArrayList _GetPhoneRegIDData = new ArrayList(); ArrayList _GetCarAlarmData = new ArrayList(); ArrayList _GetRuleInfoData = new ArrayList(); ArrayList _IOSRegIDData = new ArrayList(); ArrayList _RegIDData = new ArrayList(); _GetCarAlarmData.Add(info.DeviceID); IDataReader reader1 = DataProvider.Instance().ChkPhoneDriverInfoDB(_GetCarAlarmData);//FMS_PhoneDriverInfo_Fetch;return CarNo,Driver if (reader1.Read()) { Info1.type = "alert"; Info2.CarNo = reader1.GetString(0); Info2.Driver = reader1.GetString(1); } CBO.CloseDataReader(reader1, true); _GetRuleInfoData.Add(info.AlertRuleID); IDataReader reader2 = DataProvider.Instance().ChkPhoneRuleDB(_GetRuleInfoData);//FMS_PhoneRule_Fetch;return RuleName,AlarmType,Severity if (reader2.Read()) { Info2.AlertDate = info.EventTime; Info2.RuleName = reader2.GetString(0); Info2.AlarmType = reader2.GetString(1); Info2.Severity = reader2.GetString(2); } CBO.CloseDataReader(reader2, true); Info1.data = new string[] { JsonConvert.SerializeObject(Info2) }; string output = JsonConvert.SerializeObject(Info1); output = output.Replace("\\", "").Replace("[\"", "[").Replace("\"]", "]"); _GetPhoneRegIDData.Add(info.AlertRuleID); _GetPhoneRegIDData.Add(info.DeviceID); IDataReader reader = DataProvider.Instance().GetBaiduDB(_GetPhoneRegIDData);//FMS_PhoneBaidu_Fetch;return UserId,RegisterID,Phone_Mail_Logic BaiduSender _BaiduPush = new BaiduSender(); string strResultJson; while (reader.Read()) { info.userID = reader.GetInt32(0).ToString(); info.RegID = reader.GetString(1); Random rnd = new Random(Guid.NewGuid().GetHashCode()); String msgKey = rnd.NextDouble() + ""; strResultJson = _BaiduPush.Push(info.RegID, "", output, msgKey); //save log record CreatePushNoticeLog(info, output, "Baidu"); } CBO.CloseDataReader(reader, true); return true; }
protected bool TryGetOnlineInfo(Guid mediaItemId, IDictionary <Guid, IList <MediaItemAspect> > aspects, out BaseInfo onlineInfo) { onlineInfo = null; if (aspects.ContainsKey(PersonAspect.ASPECT_ID)) { PersonInfo personInfo = new PersonInfo(); personInfo.FromMetadata(aspects); if (personInfo.Occupation == PersonAspect.OCCUPATION_ARTIST || personInfo.Occupation == PersonAspect.OCCUPATION_COMPOSER) { onlineInfo = personInfo; } } else if (aspects.ContainsKey(CompanyAspect.ASPECT_ID)) { CompanyInfo companyInfo = new CompanyInfo(); companyInfo.FromMetadata(aspects); if (companyInfo.Type == CompanyAspect.COMPANY_MUSIC_LABEL) { onlineInfo = companyInfo; } } return(onlineInfo != null); }
//---------------------新增 baidu 註冊--------------------------------------------------------- public bool InsertBaiduPhoneRegister(BaseInfo baseInfo) { PhoneRecordInfo info = (PhoneRecordInfo)baseInfo; InsertBaiduDB(info); return true; }
/// <summary> /// Set specified ForumInfo object property according to specified value /// </summary> /// <param name="forumObj">Forum object to update with new value</param> /// <param name="propertyName">Property to be set</param> public void SetThreeStateValue(BaseInfo infoObj, string propertyName) { int value = ValidationHelper.GetInteger(Value, -1); if (value == -1) { infoObj.SetValue(propertyName, null); } else { infoObj.SetValue(propertyName, ValidationHelper.GetBoolean(value, false)); } }
private void ParseProp(BaseInfo info) { // No additional info here var fn = Path.GetFileNameWithoutExtension(info.AssetName); if (info.AssetName.EndsWith(".obj")) { bool isLevel = info.AssetName.Contains("levels"); builder.AddAsset(fn + ".hull", true, info.AssetName); builder.BeginComponent("PhysicsComponent"); builder.AddParameter("static", "true"); builder.AddParameter("physData", fn + ".hull"); builder.AddParameter("type", isLevel ? "trimesh" : "hull"); builder.EndComponent(); if (isLevel) { builder.BeginComponent("TerrainComponent"); builder.AddParameter("physData", fn + ".hull"); builder.EndComponent(); } } }
protected object grid_OnExternalDataBound(object sender, string sourceName, object parameter) { DataRowView drv = null; if (parameter is DataRowView) { drv = (DataRowView)parameter; } else if (parameter is GridViewRow) { drv = (DataRowView)((GridViewRow)parameter).DataItem; } var objectSettingsId = ValidationHelper.GetInteger(drv["ObjectSettingsID"], 0); if ((tmpObjectSettings == null) || (tmpObjectSettings.ObjectSettingsID != objectSettingsId)) { tmpObjectSettings = ObjectSettingsInfoProvider.GetObjectSettingsInfo(objectSettingsId); if (tmpObjectSettings != null) { tmpInfo = BaseAbstractInfoProvider.GetInfoById(tmpObjectSettings.ObjectSettingsObjectType, tmpObjectSettings.ObjectSettingsObjectID); } } if ((tmpInfo != null) && (tmpObjectSettings != null)) { contextResolver.SetNamedSourceData("EditedObject", tmpInfo); switch (sourceName.ToLowerCSafe()) { case "edit": var editButton = (CMSGridActionButton)sender; var url = tmpInfo.Generalized.GetEditingPageURL(); if (!string.IsNullOrEmpty(url)) { url = contextResolver.ResolveMacros(url); // Resolve dialog relative url if (url.StartsWith("~/")) { url = AuthenticationHelper.ResolveDialogUrl(url); } string queryString = URLHelper.GetQuery(url); if (queryString.IndexOfCSafe("&hash=", true) < 0) { url = URLHelper.AddParameterToUrl(url, "hash", QueryHelper.GetHash(queryString)); } editButton.OnClientClick = string.Format("modalDialog('{0}', 'objectEdit', '85%', '85%'); return false", url); } else { editButton.Enabled = false; } break; case "checkin": var checkinButton = (CMSGridActionButton)sender; if (tmpInfo.TypeInfo.SupportsLocking) { checkinButton.OnClientClick = GetConfirmScript(GetString("ObjectEditMenu.CheckInConfirmation"), tmpObjectSettings.ObjectSettingsObjectType, tmpObjectSettings.ObjectSettingsObjectID, btnCheckIn); } else { checkinButton.Enabled = false; } break; case "undocheckout": var undoCheckoutButton = (CMSGridActionButton)sender; if (tmpInfo.TypeInfo.SupportsLocking) { undoCheckoutButton.OnClientClick = GetConfirmScript(CMSObjectManager.GetUndoCheckOutConfirmation(tmpInfo, null), tmpObjectSettings.ObjectSettingsObjectType, tmpObjectSettings.ObjectSettingsObjectID, btnUndoCheckOut); } else { undoCheckoutButton.Enabled = false; } break; } } return parameter; }
/// <summary> /// Asynchronously tries to extract metadata for the given <param name="mediaItemAccessor"></param> /// </summary> /// <param name="mediaItemAccessor">Points to the resource for which we try to extract metadata</param> /// <param name="extractedAspectData">Dictionary of <see cref="MediaItemAspect"/>s with the extracted metadata</param> /// <param name="forceQuickMode">If <c>true</c>, nothing is downloaded from the internet</param> /// <returns><c>true</c> if metadata was found and stored into <param name="extractedAspectData"></param>, else <c>false</c></returns> private async Task <bool> TryExtractAudioMetadataAsync(IResourceAccessor mediaItemAccessor, IDictionary <Guid, IList <MediaItemAspect> > extractedAspectData, bool forceQuickMode) { // Get a unique number for this call to TryExtractMetadataAsync. We use this to make reading the debug log easier. // This MetadataExtractor is called in parallel for multiple MediaItems so that the respective debug log entries // for one call are not contained one after another in debug log. We therefore prepend this number before every log entry. var miNumber = Interlocked.Increment(ref _lastMediaItemNumber); bool isStub = extractedAspectData.ContainsKey(StubAspect.ASPECT_ID); if (!isStub) { _debugLogger.Info("[#{0}]: Ignoring non-stub track", miNumber); return(false); } try { _debugLogger.Info("[#{0}]: Start extracting metadata for resource '{1}' (forceQuickMode: {2})", miNumber, mediaItemAccessor, forceQuickMode); // We only extract metadata with this MetadataExtractor, if another MetadataExtractor that was applied before // has identified this MediaItem as a video and therefore added a VideoAspect. if (!extractedAspectData.ContainsKey(AudioAspect.ASPECT_ID)) { _debugLogger.Info("[#{0}]: Cannot extract metadata; this resource is not audio", miNumber); return(false); } // This MetadataExtractor only works for MediaItems accessible by an IFileSystemResourceAccessor. // Otherwise it is not possible to find a nfo-file in the MediaItem's directory. if (!(mediaItemAccessor is IFileSystemResourceAccessor)) { _debugLogger.Info("[#{0}]: Cannot extract metadata; mediaItemAccessor is not an IFileSystemResourceAccessor", miNumber); return(false); } // First we try to find an IFileSystemResourceAccessor pointing to the album nfo-file. IFileSystemResourceAccessor albumNfoFsra; if (TryGetAlbumNfoSResourceAccessor(miNumber, mediaItemAccessor as IFileSystemResourceAccessor, out albumNfoFsra)) { // If we found one, we (asynchronously) extract the metadata into a stub object and, if metadata was found, // we store it into the MediaItemAspects. var albumNfoReader = new NfoAlbumReader(_debugLogger, miNumber, forceQuickMode, isStub, _httpClient, _settings); using (albumNfoFsra) { if (await albumNfoReader.TryReadMetadataAsync(albumNfoFsra).ConfigureAwait(false)) { //Check reimport if (extractedAspectData.ContainsKey(ReimportAspect.ASPECT_ID)) { AlbumInfo reimport = new AlbumInfo(); reimport.FromMetadata(extractedAspectData); if (!VerifyAlbumReimport(albumNfoReader, reimport)) { ServiceRegistration.Get <ILogger>().Info("NfoMovieMetadataExtractor: Nfo album metadata from resource '{0}' ignored because it does not match reimport {1}", mediaItemAccessor, reimport); return(false); } } Stubs.AlbumStub album = albumNfoReader.GetAlbumStubs().FirstOrDefault(); if (album != null) { int trackNo = 0; if (album.Tracks != null && album.Tracks.Count > 0 && MediaItemAspect.TryGetAttribute(extractedAspectData, AudioAspect.ATTR_TRACK, out trackNo)) { var track = album.Tracks.FirstOrDefault(t => t.TrackNumber.HasValue && trackNo == t.TrackNumber.Value); if (track != null) { TrackInfo trackInfo = new TrackInfo(); string title; string sortTitle; title = track.Title.Trim(); sortTitle = BaseInfo.GetSortTitle(title); IEnumerable <string> artists; if (track.Artists.Count > 0) { artists = track.Artists; } IList <MultipleMediaItemAspect> providerResourceAspects; if (MediaItemAspect.TryGetAspects(extractedAspectData, ProviderResourceAspect.Metadata, out providerResourceAspects)) { MultipleMediaItemAspect providerResourceAspect = providerResourceAspects.First(pa => pa.GetAttributeValue <int>(ProviderResourceAspect.ATTR_TYPE) == ProviderResourceAspect.TYPE_STUB); string mime = null; if (track.FileInfo != null && track.FileInfo.Count > 0) { mime = MimeTypeDetector.GetMimeTypeFromExtension("file" + track.FileInfo.First().Container); } if (mime != null) { providerResourceAspect.SetAttribute(ProviderResourceAspect.ATTR_MIME_TYPE, mime); } } trackInfo.TrackName = title; trackInfo.TrackNameSort = sortTitle; trackInfo.Duration = track.Duration.HasValue ? Convert.ToInt64(track.Duration.Value.TotalSeconds) : 0; trackInfo.Album = !string.IsNullOrEmpty(album.Title) ? album.Title.Trim() : null; trackInfo.TrackNum = track.TrackNumber.HasValue ? track.TrackNumber.Value : 0; trackInfo.TotalTracks = album.Tracks.Count; trackInfo.MusicBrainzId = track.MusicBrainzId; trackInfo.IsrcId = track.Isrc; trackInfo.AudioDbId = track.AudioDbId.HasValue ? track.AudioDbId.Value : 0; trackInfo.AlbumMusicBrainzId = album.MusicBrainzAlbumId; trackInfo.AlbumMusicBrainzGroupId = album.MusicBrainzReleaseGroupId; trackInfo.ReleaseDate = album.ReleaseDate; if (track.FileInfo != null && track.FileInfo.Count > 0 && track.FileInfo.First().AudioStreams != null && track.FileInfo.First().AudioStreams.Count > 0) { var audio = track.FileInfo.First().AudioStreams.First(); trackInfo.Encoding = audio.Codec; trackInfo.BitRate = audio.Bitrate != null?Convert.ToInt32(audio.Bitrate / 1000) : 0; trackInfo.Channels = audio.Channels != null ? audio.Channels.Value : 0; } trackInfo.Artists = new List <PersonInfo>(); if (track.Artists != null && track.Artists.Count > 0) { foreach (string artistName in track.Artists) { trackInfo.Artists.Add(new PersonInfo() { Name = artistName.Trim(), Occupation = PersonAspect.OCCUPATION_ARTIST, ParentMediaName = trackInfo.Album, MediaName = trackInfo.TrackName }); } } trackInfo.AlbumArtists = new List <PersonInfo>(); if (album.Artists != null && album.Artists.Count > 0) { foreach (string artistName in album.Artists) { trackInfo.AlbumArtists.Add(new PersonInfo() { Name = artistName.Trim(), Occupation = PersonAspect.OCCUPATION_ARTIST, ParentMediaName = trackInfo.Album, MediaName = trackInfo.TrackName }); } } if (album.Genres != null && album.Genres.Count > 0) { trackInfo.Genres = album.Genres.Where(s => !string.IsNullOrEmpty(s?.Trim())).Select(s => new GenreInfo { Name = s.Trim() }).ToList(); IGenreConverter converter = ServiceRegistration.Get <IGenreConverter>(); foreach (var genre in trackInfo.Genres) { if (!genre.Id.HasValue && converter.GetGenreId(genre.Name, GenreCategory.Music, null, out int genreId)) { genre.Id = genreId; } } } if (album.Thumb != null && album.Thumb.Length > 0) { try { using (MemoryStream stream = new MemoryStream(album.Thumb)) { trackInfo.Thumbnail = stream.ToArray(); trackInfo.HasChanged = true; } } // Decoding of invalid image data can fail, but main MediaItem is correct. catch { } } //Determine compilation if (trackInfo.AlbumArtists.Count > 0 && (trackInfo.AlbumArtists[0].Name.IndexOf("Various", StringComparison.InvariantCultureIgnoreCase) >= 0 || trackInfo.AlbumArtists[0].Name.Equals("VA", StringComparison.InvariantCultureIgnoreCase))) { trackInfo.Compilation = true; } else { //Look for itunes compilation folder var mediaItemPath = mediaItemAccessor.CanonicalLocalResourcePath; var artistMediaItemDirectoryPath = ResourcePathHelper.Combine(mediaItemPath, "../../"); if (artistMediaItemDirectoryPath.FileName.IndexOf("Compilation", StringComparison.InvariantCultureIgnoreCase) >= 0) { trackInfo.Compilation = true; } } trackInfo.SetMetadata(extractedAspectData); } } } } else { _debugLogger.Warn("[#{0}]: No valid metadata found in album nfo-file", miNumber); } } } _debugLogger.Info("[#{0}]: Successfully finished extracting metadata", miNumber); ServiceRegistration.Get <ILogger>().Debug("NfoAudioMetadataExtractor: Assigned nfo audio metadata for resource '{0}'", mediaItemAccessor); return(true); } catch (Exception e) { ServiceRegistration.Get <ILogger>().Warn("NfoAudioMetadataExtractor: Exception while extracting metadata for resource '{0}'; enable debug logging for more details.", mediaItemAccessor); _debugLogger.Error("[#{0}]: Exception while extracting metadata", e, miNumber); return(false); } }
/// <summary> /// Initializes menu with view mode selection. /// </summary> private void InitializeActionsMenu() { if ((SourceType != MediaSourceEnum.DocumentAttachments) && (SourceType != MediaSourceEnum.MetaFile)) { string selectors = (IsLiveSite ? "LiveSelectors" : "Selectors"); // Get new folder dialog URL if (SourceType == MediaSourceEnum.MediaLibraries) { WindowHelper.Remove(Identifier); Hashtable properties = new Hashtable(); properties.Add("libraryid", LibraryID); properties.Add("path", LibraryFolderPath); properties.Add("cancel", false); WindowHelper.Add(Identifier, properties); if (IsLiveSite) { if (CMSContext.CurrentUser.IsAuthenticated()) { NewFolderDialogUrl = "~/CMS/Dialogs/CMSModules/MediaLibrary/FormControls/LiveSelectors/InsertImageOrMedia/NewMediaFolder.aspx?identifier=" + Identifier; } else { NewFolderDialogUrl = "~/CMSModules/MediaLibrary/FormControls/LiveSelectors/InsertImageOrMedia/NewMediaFolder.aspx?identifier=" + Identifier; } } else { NewFolderDialogUrl = "~/CMSModules/MediaLibrary/FormControls/Selectors/InsertImageOrMedia/NewMediaFolder.aspx?identifier=" + Identifier; } } else { NewFolderDialogUrl = "~/CMSFormControls/" + selectors + "/InsertImageOrMedia/NewCMSFolder.aspx?nodeid=" + NodeID + "&culture=" + Config.Culture; } // Add security hash NewFolderDialogUrl = URLHelper.AddParameterToUrl(NewFolderDialogUrl, "hash", QueryHelper.GetHash(NewFolderDialogUrl, false)); menuBtnNewFolder.Tooltip = GetString("dialogs.actions.newfolder.desc"); menuBtnNewFolder.OnClickJavascript = "modalDialog('" + URLHelper.ResolveUrl(NewFolderDialogUrl) + "', 'NewFolder', 500, 350, null, true); return false;"; menuBtnNewFolder.Text = "<div style=\"overflow:hidden; width:66px; white-space:nowrap\">" + GetString("dialogs.actions.newfolder") + "</div>"; } else { // Hide New folder button for attachments menuBtnNewFolder.Visible = false; plcActionsMenu.Visible = false; pnlLeft.CssClass += " Smaller "; } // Initialize disabled button imgUploaderDisabled.EnableViewState = false; imgUploaderDisabled.Alt = GetString("dialogs.actions.newfile"); // If attachments are being displayed and no document or form is specified - hide uploader if (!IsCopyMoveLinkDialog && (((SourceType != MediaSourceEnum.DocumentAttachments) && (SourceType != MediaSourceEnum.MetaFile)) || ((SourceType == MediaSourceEnum.DocumentAttachments) && (Config.AttachmentDocumentID > 0 || Config.AttachmentFormGUID != Guid.Empty)) || ((SourceType == MediaSourceEnum.MetaFile) && ((MetaFileObjectID > 0) && !string.IsNullOrEmpty(MetaFileObjectType) && !string.IsNullOrEmpty(MetaFileCategory))))) { // Initialize file uploader if (SourceType == MediaSourceEnum.MetaFile) { fileUploader.ObjectID = MetaFileObjectID; fileUploader.ObjectType = MetaFileObjectType; fileUploader.Category = MetaFileCategory; BaseInfo info = BaseAbstractInfoProvider.GetInfoById(MetaFileObjectType, MetaFileObjectID); fileUploader.SiteID = info != null ? info.Generalized.ObjectSiteID : CMSContext.CurrentSiteID; } else { fileUploader.DocumentID = DocumentID; fileUploader.FormGUID = FormGUID; fileUploader.NodeParentNodeID = ((NodeID > 0) ? NodeID : ParentNodeID); fileUploader.NodeClassName = URLHelper.EncodeQueryString("CMS.File"); fileUploader.LibraryID = LibraryID; fileUploader.LibraryFolderPath = LibraryFolderPath; fileUploader.ResizeToHeight = ResizeToHeight; fileUploader.ResizeToMaxSideSize = ResizeToMaxSideSize; fileUploader.ResizeToWidth = ResizeToWidth; fileUploader.CheckPermissions = true; } fileUploader.ParentElemID = CMSDialogHelper.GetMediaSource(SourceType); fileUploader.SourceType = SourceType; fileUploader.IsLiveSite = IsLiveSite; fileUploader.InnerDivClass = "DialogMenuInnerDiv"; fileUploader.InnerDivHtml = String.Format("<span>{0}</span>", GetString("dialogs.actions.newfile")); fileUploader.LoadingImageUrl = GetImageUrl("Design/Preloaders/preload16.gif"); fileUploader.InnerLoadingDivHtml = " "; fileUploader.UploadMode = MultifileUploaderModeEnum.DirectMultiple; } else { plcDirectFileUploader.Visible = false; fileUploader.StopProcessing = true; } }
protected object grid_OnExternalDataBound(object sender, string sourceName, object parameter) { DataRowView drv = null; if (parameter is DataRowView) { drv = (DataRowView)parameter; } else if (parameter is GridViewRow) { drv = (DataRowView)((GridViewRow)parameter).DataItem; } var objectSettingsId = ValidationHelper.GetInteger(drv["ObjectSettingsID"], 0); if ((tmpObjectSettings == null) || (tmpObjectSettings.ObjectSettingsID != objectSettingsId)) { tmpObjectSettings = ObjectSettingsInfoProvider.GetObjectSettingsInfo(objectSettingsId); tmpInfo = CMSObjectHelper.GetObjectById(tmpObjectSettings.ObjectSettingsObjectType, tmpObjectSettings.ObjectSettingsObjectID); } contextResolver.SetNamedSourceData("EditedObject", tmpInfo); switch (sourceName.ToLowerCSafe()) { case "edit": var editButton = (CMSImageButton)sender; var url = tmpInfo.Generalized.GetEditingPageURL(); if (!string.IsNullOrEmpty(url)) { url = contextResolver.ResolveMacros(url); url = CMSContext.ResolveDialogUrl(url); var queryString = URLHelper.GetQuery(url); url = URLHelper.AddParameterToUrl(url, "hash", QueryHelper.GetHash(queryString)); editButton.OnClientClick = string.Format("modalDialog('{0}', 'objectEdit', '85%', '85%');", url); } else { editButton.Enabled = false; } break; case "checkin": var checkinButton = (CMSImageButton)sender; checkinButton.ImageUrl = GetImageUrl("CMSModules/CMS_Content/EditMenu/16/checkin.png"); if (tmpInfo.TypeInfo.SupportsLocking) { checkinButton.Attributes["onclick"] = GetConfirmScript(GetString("ObjectEditMenu.CheckInConfirmation"), tmpObjectSettings.ObjectSettingsObjectType, tmpObjectSettings.ObjectSettingsObjectID, btnCheckIn); } else { checkinButton.Enabled = false; } break; case "undocheckout": var undoCheckoutButton = (CMSImageButton)sender; undoCheckoutButton.ImageUrl = GetImageUrl("CMSModules/CMS_Content/EditMenu/16/undocheckout.png"); if (tmpInfo.TypeInfo.SupportsLocking) { undoCheckoutButton.Attributes["onclick"] = GetConfirmScript(CMSObjectManager.GetUndoCheckOutConfirmation(tmpInfo, null), tmpObjectSettings.ObjectSettingsObjectType, tmpObjectSettings.ObjectSettingsObjectID, btnUndoCheckOut); } else { undoCheckoutButton.Enabled = false; } break; } return parameter; }
public bool TryExtractRelationships(IDictionary <Guid, IList <MediaItemAspect> > aspects, bool importOnly, out IList <RelationshipItem> extractedLinkedAspects) { extractedLinkedAspects = null; SeasonInfo seasonInfo = new SeasonInfo(); if (!seasonInfo.FromMetadata(aspects)) { return(false); } if (CheckCacheContains(seasonInfo)) { return(false); } SeriesInfo cachedSeries; Guid seriesId; SeriesInfo seriesInfo = seasonInfo.CloneBasicInstance <SeriesInfo>(); if (TryGetInfoFromCache(seriesInfo, out cachedSeries, out seriesId)) { seriesInfo = cachedSeries; } else if (!SeriesMetadataExtractor.SkipOnlineSearches) { OnlineMatcherService.Instance.UpdateSeries(seriesInfo, false, importOnly); } if (!BaseInfo.HasRelationship(aspects, LinkedRole)) { seriesInfo.HasChanged = true; //Force save if no relationship exists } if (!seriesInfo.HasChanged && !importOnly) { return(false); } AddToCheckCache(seasonInfo); extractedLinkedAspects = new List <RelationshipItem>(); IDictionary <Guid, IList <MediaItemAspect> > seriesAspects = new Dictionary <Guid, IList <MediaItemAspect> >(); seriesInfo.SetMetadata(seriesAspects); if (aspects.ContainsKey(EpisodeAspect.ASPECT_ID)) { bool episodeVirtual = true; if (MediaItemAspect.TryGetAttribute(aspects, MediaAspect.ATTR_ISVIRTUAL, false, out episodeVirtual)) { MediaItemAspect.SetAttribute(seriesAspects, MediaAspect.ATTR_ISVIRTUAL, episodeVirtual); } } if (!seriesAspects.ContainsKey(ExternalIdentifierAspect.ASPECT_ID)) { return(false); } if (seriesId != Guid.Empty) { extractedLinkedAspects.Add(new RelationshipItem(seriesAspects, seriesId)); } else { extractedLinkedAspects.Add(new RelationshipItem(seriesAspects, Guid.Empty)); } return(true); }
/// <summary> /// Get ForumInfo object value to initialize ThreeStateControl object /// </summary> /// <param name="forumObj">ForumInfo object used to initialize ThreeStateControl</param> /// <param name="propertyName">Object property used for initialization</param> /// <returns>Integer value used to initialize ThreeStateControl </returns> public void InitFromThreeStateValue(BaseInfo infoObj, string propertyName) { object dbValue = infoObj.GetValue(propertyName); Value = (dbValue == null) ? -1 : ValidationHelper.GetBoolean(dbValue, true) ? 1 : 0; }
/// <summary> /// Imports default metafiles which were changed in the new version. /// </summary> /// <param name="upgradeFolder">Folder where the generated metafiles.xml file is</param> private static void ImportMetaFiles(string upgradeFolder) { try { // To get the file use Phobos - Generate files button, Metafile settings. // Choose only those object types which had metafiles in previous version and these metafiles changed to the new version. String xmlPath = Path.Combine(upgradeFolder, "metafiles.xml"); if (File.Exists(xmlPath)) { XmlDocument xDoc = new XmlDocument(); xDoc.Load(xmlPath); XmlNode metaFilesNode = xDoc.SelectSingleNode("MetaFiles"); if (metaFilesNode == null) { return; } String filesDirectory = Path.Combine(upgradeFolder, "Metafiles"); using (new CMSActionContext { LogEvents = false }) { foreach (XmlNode metaFile in metaFilesNode) { // Load metafiles information from XML if (metaFile.Attributes == null) { continue; } String objType = metaFile.Attributes["ObjectType"].Value; String groupName = metaFile.Attributes["GroupName"].Value; String codeName = metaFile.Attributes["CodeName"].Value; String fileName = metaFile.Attributes["FileName"].Value; String extension = metaFile.Attributes["Extension"].Value; String fileGUID = metaFile.Attributes["FileGUID"].Value; String title = (metaFile.Attributes["Title"] != null) ? metaFile.Attributes["Title"].Value : null; String description = (metaFile.Attributes["Description"] != null) ? metaFile.Attributes["Description"].Value : null; // Try to find correspondent info object BaseInfo infoObject = ProviderHelper.GetInfoByName(objType, codeName); if (infoObject == null) { continue; } int infoObjectId = infoObject.Generalized.ObjectID; // Check if metafile exists InfoDataSet <MetaFileInfo> metaFilesSet = MetaFileInfoProvider.GetMetaFilesWithoutBinary(infoObjectId, objType, groupName, "MetaFileGUID = '" + fileGUID + "'", null); if (!DataHelper.DataSourceIsEmpty(metaFilesSet)) { continue; } // Create new metafile if does not exists String mfFileName = String.Format("{0}.{1}", fileGUID, extension.TrimStart('.')); MetaFileInfo mfInfo = new MetaFileInfo(Path.Combine(filesDirectory, mfFileName), infoObjectId, objType, groupName); mfInfo.MetaFileGUID = ValidationHelper.GetGuid(fileGUID, Guid.NewGuid()); // Set correct properties mfInfo.MetaFileName = fileName; if (title != null) { mfInfo.MetaFileTitle = title; } if (description != null) { mfInfo.MetaFileDescription = description; } // Save new meta file MetaFileInfoProvider.SetMetaFileInfo(mfInfo); } // Remove existing files after successful finish String[] files = Directory.GetFiles(upgradeFolder); foreach (String file in files) { File.Delete(file); } } } } catch (Exception ex) { EventLogProvider.LogException(EventLogSource, "IMPORTMETAFILES", ex); } }
private void ReloadMenu() { if (StopProcessing) { return; } bool displayObjectMenu = false; BaseInfo editInfo = InfoObject ?? ModuleManager.GetReadOnlyObject(ObjectManager.ObjectType); if (editInfo != null) { // Do not display items when object does not support locking and when there is no associated UIForm displayObjectMenu = editInfo.TypeInfo.SupportsLocking && ObjectManager.ShowPanel; } if (displayObjectMenu) { // Handle several reloads menu.ActionsList.Clear(); ClearProperties(); if (!HideStandardButtons) { // Handle save action if (ShowSave) { save = new SaveAction { Tooltip = ResHelper.GetString("EditMenu.Save", ResourceCulture), Enabled = AllowSave, EventName = "", CommandName = "", Index = -2 }; if (AllowSave) { string script = RaiseGetClientActionScript(ComponentEvents.SAVE); script += RaiseGetClientValidationScript(ComponentEvents.SAVE, ObjectManager.GetJSFunction(ComponentEvents.SAVE, null, null)); save.OnClientClick = script; } AddAction(save); } // Object update if (SynchronizationHelper.UseCheckinCheckout && (ObjectManager.Mode == FormModeEnum.Update)) { if (InfoObject != null) { if (ShowCheckOut) { checkout = new HeaderAction { Tooltip = ResHelper.GetString("ObjectEditMenu.Checkout", ResourceCulture), Text = ResHelper.GetString("EditMenu.IconCheckout", ResourceCulture), Enabled = AllowCheckOut }; if (AllowCheckOut) { string script = RaiseGetClientActionScript(ComponentEvents.CHECKOUT); script += RaiseGetClientValidationScript(ComponentEvents.CHECKOUT, ObjectManager.GetJSFunction(ComponentEvents.CHECKOUT, null, null)); checkout.OnClientClick = script; } AddAction(checkout); } if (ShowUndoCheckOut) { undocheckout = new HeaderAction { Tooltip = ResHelper.GetString("ObjectEditMenu.UndoCheckOut", ResourceCulture), Text = ResHelper.GetString("EditMenu.IconUndoCheckout", ResourceCulture), Enabled = AllowUndoCheckOut }; if (AllowUndoCheckOut) { string script = RaiseGetClientActionScript(ComponentEvents.UNDO_CHECKOUT); script += RaiseGetClientValidationScript(ComponentEvents.UNDO_CHECKOUT, ObjectManager.GetJSFunction(ComponentEvents.UNDO_CHECKOUT, null, null)); undocheckout.OnClientClick = script; } AddAction(undocheckout); } if (ShowCheckIn) { checkin = new HeaderAction { Tooltip = ResHelper.GetString("ObjectEditMenu.Checkin", ResourceCulture), Text = ResHelper.GetString("EditMenu.IconCheckin", ResourceCulture), Enabled = AllowCheckIn }; if (AllowCheckIn) { string script = RaiseGetClientActionScript(ComponentEvents.CHECKIN); script += RaiseGetClientValidationScript(ComponentEvents.CHECKIN, ObjectManager.GetJSFunction(ComponentEvents.CHECKIN, null, null)); checkin.OnClientClick = script; } if (ShowCheckInWithComment) { AddCommentAction(ComponentEvents.CHECKIN, checkin); } else { AddAction(checkin); } } } } } } // Add extra actions if (ObjectManager.ShowPanel && (mExtraActions != null)) { foreach (HeaderAction action in mExtraActions) { AddAction(action); } } }
/// <summary> /// Generates where condition. /// </summary> protected string GenerateWhereCondition(int siteId) { switch (FilterMode) { case "user": { // If some site selected filter users if (siteId > 0) { return("UserID IN (SELECT UserID FROM CMS_UserSite WHERE SiteID = " + siteId + ")"); } } break; case "role": { // If some site selected filter users if (siteId > 0) { return("SiteID = " + siteId); } if (siteId.ToString() == siteSelector.GlobalRecordValue) { return("SiteID IS NULL"); } } break; case "subscriber": { // If some site filters subscribers if (siteId > 0) { return("SubscriberSiteID = " + siteId); } } break; case "cultures": { if (siteId > 0) { return("CultureID IN (SELECT CultureID FROM CMS_SiteCulture WHERE SiteID = " + siteId + ")"); } } break; case "bizform": { if (siteId > 0) { return("FormSiteID = " + siteId); } } break; case "notificationtemplate": case "notificationtemplateglobal": { string where; // Set the prefix for the item SiteInfo si = SiteInfoProvider.GetSiteInfo(siteId); if (si != null) { filteredControl.SetValue("ItemPrefix", si.SiteName + "."); where = "TemplateSiteID = " + siteId; } // Add global templates else { filteredControl.SetValue("ItemPrefix", null); where = "TemplateSiteID IS NULL"; } return(where); } case "department": { // If some site selected filter departments if (siteId > 0) { return("DepartmentSiteID = " + siteId); } if (siteId.ToString() == siteSelector.GlobalRecordValue) { return("DepartmentSiteID IS NULL"); } } break; default: { // Automatic filtering mode if ((siteId > 0) || (siteId == UniSelector.US_GLOBAL_RECORD)) { IObjectTypeDriven filtered = FilteredControl as IObjectTypeDriven; if (filtered != null) { BaseInfo infoObj = ModuleManager.GetReadOnlyObject(filtered.ObjectType); return(infoObj.TypeInfo.GetSiteWhereCondition(siteId, false).ToString(true)); } } } break; } return(String.Empty); }
private static DataTable CreateDataTable(IEnumerable<BaseInfo> data, BaseInfo info) { DataTable table = new DataTable(); var columns = ExtractDataColumns(info).ToArray(); if (!columns.Any()) { return table; } table.Columns.AddRange(columns); foreach (BaseInfo item in data) { DataRow row = table.NewRow(); FillDataRow(item, row); table.Rows.Add(row); } return table; }
public virtual bool TryExtractMetadata(IResourceAccessor mediaItemAccessor, IDictionary <Guid, IList <MediaItemAspect> > extractedAspectData, bool importOnly, bool forceQuickMode) { try { IResourceAccessor metaFileAccessor; if (!CanExtract(mediaItemAccessor, extractedAspectData, out metaFileAccessor)) { return(false); } Tags tags; using (metaFileAccessor) { using (Stream metaStream = ((IFileSystemResourceAccessor)metaFileAccessor).OpenRead()) tags = (Tags)GetTagsXmlSerializer().Deserialize(metaStream); } string value; MediaItemAspect.SetAttribute(extractedAspectData, MediaAspect.ATTR_ISVIRTUAL, false); MediaItemAspect.SetAttribute(extractedAspectData, VideoAspect.ATTR_ISDVD, false); if (TryGet(tags, TAG_TITLE, out value) && !string.IsNullOrEmpty(value)) { MediaItemAspect.SetAttribute(extractedAspectData, MediaAspect.ATTR_TITLE, value); MediaItemAspect.SetAttribute(extractedAspectData, MediaAspect.ATTR_SORT_TITLE, BaseInfo.GetSortTitle(value)); } if (TryGet(tags, TAG_GENRE, out value)) { List <GenreInfo> genreList = new List <GenreInfo>(new GenreInfo[] { new GenreInfo { Name = value } }); OnlineMatcherService.Instance.AssignMissingMovieGenreIds(genreList); MultipleMediaItemAspect genreAspect = MediaItemAspect.CreateAspect(extractedAspectData, GenreAspect.Metadata); genreAspect.SetAttribute(GenreAspect.ATTR_ID, genreList[0].Id); genreAspect.SetAttribute(GenreAspect.ATTR_GENRE, genreList[0].Name); } if (TryGet(tags, TAG_PLOT, out value)) { MediaItemAspect.SetAttribute(extractedAspectData, VideoAspect.ATTR_STORYPLOT, value); Match yearMatch = _yearMatcher.Match(value); int guessedYear; if (int.TryParse(yearMatch.Value, out guessedYear)) { MediaItemAspect.SetAttribute(extractedAspectData, MediaAspect.ATTR_RECORDINGTIME, new DateTime(guessedYear, 1, 1)); } } if (TryGet(tags, TAG_CHANNEL, out value)) { MediaItemAspect.SetAttribute(extractedAspectData, RecordingAspect.ATTR_CHANNEL, value); } // Recording date formatted: 2011-11-04 20:55 DateTime recordingStart; DateTime recordingEnd; if (TryGet(tags, TAG_STARTTIME, out value) && DateTime.TryParse(value, out recordingStart)) { MediaItemAspect.SetAttribute(extractedAspectData, RecordingAspect.ATTR_STARTTIME, recordingStart); } if (TryGet(tags, TAG_ENDTIME, out value) && DateTime.TryParse(value, out recordingEnd)) { MediaItemAspect.SetAttribute(extractedAspectData, RecordingAspect.ATTR_ENDTIME, recordingEnd); } return(true); } catch (Exception e) { // Only log at the info level here - And simply return false. This lets the caller know that we // couldn't perform our task here. ServiceRegistration.Get <ILogger>().Info("Tve3RecordingMetadataExtractor: Exception reading resource '{0}' (Text: '{1}')", mediaItemAccessor.CanonicalLocalResourcePath, e.Message); } return(false); }
private static void FillDataRow(BaseInfo item, DataRow row) { var ti = item.TypeInfo; var prefix = ti.ObjectClassName.Split('.').Last(); foreach (string column in row.Table.Columns.OfType<DataColumn>().Select(c => c.ColumnName)) { if (column == ti.GUIDColumn) { var guid = Guid.NewGuid(); item.SetValue(column, guid); row[column] = guid; } else if ((column == ti.TimeStampColumn) || (column == string.Format("{0}Created", prefix))) { var date = DateTime.Now; item.SetValue(column, date); row[column] = date; } else { row[column] = item.GetValue(column) ?? DBNull.Value; } } }
protected object grid_OnExternalDataBound(object sender, string sourceName, object parameter) { DataRowView drv = null; if (parameter is DataRowView) { drv = (DataRowView)parameter; } else if (parameter is GridViewRow) { drv = (DataRowView)((GridViewRow)parameter).DataItem; } var objectSettingsId = ValidationHelper.GetInteger(drv["ObjectSettingsID"], 0); if ((tmpObjectSettings == null) || (tmpObjectSettings.ObjectSettingsID != objectSettingsId)) { tmpObjectSettings = ObjectSettingsInfoProvider.GetObjectSettingsInfo(objectSettingsId); if (tmpObjectSettings != null) { tmpInfo = ProviderHelper.GetInfoById(tmpObjectSettings.ObjectSettingsObjectType, tmpObjectSettings.ObjectSettingsObjectID); } } if ((tmpInfo != null) && (tmpObjectSettings != null)) { contextResolver.SetNamedSourceData("EditedObject", tmpInfo); switch (sourceName.ToLowerCSafe()) { case "edit": var editButton = (CMSGridActionButton)sender; var url = tmpInfo.Generalized.GetEditingPageURL(); if (!string.IsNullOrEmpty(url)) { url = contextResolver.ResolveMacros(url); // Resolve dialog relative url if (url.StartsWith("~/", StringComparison.Ordinal)) { url = ApplicationUrlHelper.ResolveDialogUrl(url); } string queryString = URLHelper.GetQuery(url); if (queryString.IndexOfCSafe("&hash=", true) < 0) { url = URLHelper.AddParameterToUrl(url, "hash", QueryHelper.GetHash(queryString)); } editButton.OnClientClick = string.Format("modalDialog('{0}', 'objectEdit', '85%', '85%'); return false", url); } else { editButton.Enabled = false; } break; case "checkin": var checkinButton = (CMSGridActionButton)sender; if (tmpInfo.TypeInfo.SupportsLocking) { checkinButton.OnClientClick = GetConfirmScript(GetString("ObjectEditMenu.CheckInConfirmation"), tmpObjectSettings.ObjectSettingsObjectType, tmpObjectSettings.ObjectSettingsObjectID, btnCheckIn); } else { checkinButton.Enabled = false; } break; case "undocheckout": var undoCheckoutButton = (CMSGridActionButton)sender; if (tmpInfo.TypeInfo.SupportsLocking) { undoCheckoutButton.OnClientClick = GetConfirmScript(CMSObjectManager.GetUndoCheckOutConfirmation(tmpInfo, null), tmpObjectSettings.ObjectSettingsObjectType, tmpObjectSettings.ObjectSettingsObjectID, btnUndoCheckOut); } else { undoCheckoutButton.Enabled = false; } break; } } return(parameter); }
/// <summary> /// Redirects to the edit page of the saved product. /// </summary> private void RedirectToSavedProduct(BaseInfo product) { string url = ProductUIHelper.GetProductEditUrl(); // Creating product options of type other than products is redirected directly to form if (OptionCategoryID > 0) { var categoryInfo = OptionCategoryInfoProvider.GetOptionCategoryInfo(OptionCategoryID); if (categoryInfo != null) { url = "Product_Edit_General.aspx"; if (categoryInfo.CategoryType == OptionCategoryTypeEnum.Products) { url = UIContextHelper.GetElementUrl("cms.ecommerce", "ProductOptions.Options.Edit", false); } } } url = URLHelper.AddParameterToUrl(url, "siteId", SiteID.ToString()); url = URLHelper.AddParameterToUrl(url, "categoryId", OptionCategoryID.ToString()); url = URLHelper.AddParameterToUrl(url, "objectid", OptionCategoryID.ToString()); if (product is TreeNode) { int nodeId = product.GetIntegerValue("NodeID", 0); url = URLHelper.AddParameterToUrl(url, "nodeId", nodeId.ToString()); } else if (product is SKUInfo) { int skuId = product.GetIntegerValue("SKUID", 0); url = URLHelper.AddParameterToUrl(url, "productId", skuId.ToString()); // Select general tab if stan-alone SKU is saved if (OptionCategoryID == 0) { url = URLHelper.AddParameterToUrl(url, "tabName", "Products.General"); } } url = URLHelper.AddParameterToUrl(url, "saved", "1"); URLHelper.Redirect(url); }
protected void Page_Load(object sender, EventArgs e) { // Get query string parameters objectType = QueryHelper.GetString("objecttype", String.Empty); int objectId = QueryHelper.GetInteger("objectid", 0); // Get the object BaseInfo info = ProviderHelper.GetInfoById(objectType, objectId); string objTypeName = ""; if (info != null) { objTypeName = GetString("objecttype." + TranslationHelper.GetSafeClassName(info.TypeInfo.ObjectType)); } if (objTypeName.StartsWithCSafe("objecttype.")) { objTypeName = ""; SetTitle(String.Format(GetString("clonning.dialog.title"), HTMLHelper.HTMLEncode(ResHelper.LocalizeString(info.Generalized.ObjectDisplayName)))); } else { SetTitle(String.Format(GetString("clonning.dialog.title"), objTypeName)); } btnClone.Text = GetString("General.Clone"); btnClone.Click += btnClone_Click; if (info == null) { ShowInformation(GetString("clonning.dialog.objectdoesnotexist")); cloneObjectElem.Visible = false; return; } if (cloneObjectElem.HasNoSettings()) { ShowInformation(String.Format(GetString("clonning.settings.emptyinfobox"), objTypeName, HTMLHelper.HTMLEncode(ResHelper.LocalizeString(info.Generalized.ObjectDisplayName)))); } else { ShowInformation(String.Format(GetString("clonning.settings.infobox"), objTypeName, HTMLHelper.HTMLEncode(ResHelper.LocalizeString(info.Generalized.ObjectDisplayName)))); } // Check permissions if (!info.CheckPermissions(PermissionsEnum.Read, CurrentSiteName, CurrentUser)) { RedirectToAccessDenied(info.TypeInfo.ModuleName, "read"); } cloneObjectElem.InfoToClone = info; // Register refresh script to refresh wopener StringBuilder script = new StringBuilder(); script.Append(@" function RefreshContent() { if (wopener != null) { if (wopener.RefreshWOpener) { window.refreshPageOnClose = true; wopener.RefreshWOpener(window); } else { wopener.window.location.replace(wopener.window.location); } } }"); // Register script ScriptHelper.RegisterWOpenerScript(Page); ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "WOpenerRefresh", ScriptHelper.GetScript(script.ToString())); }
/// <summary> /// Redirects to the edit page of the saved product. /// </summary> private void RedirectToSavedProduct(BaseInfo product) { string url = "Product_Edit_Frameset.aspx"; url = URLHelper.AddParameterToUrl(url, "siteId", SiteID.ToString()); url = URLHelper.AddParameterToUrl(url, "categoryId", OptionCategoryID.ToString()); if (product is TreeNode) { int nodeId = product.GetIntegerValue("NodeID", 0); url = URLHelper.AddParameterToUrl(url, "nodeId", nodeId.ToString()); } else if (product is SKUInfo) { int skuId = product.GetIntegerValue("SKUID", 0); url = URLHelper.AddParameterToUrl(url, "productId", skuId.ToString()); } url = URLHelper.AddParameterToUrl(url, "saved", "1"); URLHelper.Redirect(url); }
protected void Page_Load(object sender, EventArgs e) { mEditedObject = UIContext.EditedObject as BaseInfo; // If saved is found in query string if (!RequestHelper.IsPostBack() && (QueryHelper.GetInteger("saved", 0) == 1)) { ShowChangesSaved(); } string before; string after; string objectType = UIContextHelper.GetObjectType(UIContext); switch (objectType.ToLowerCSafe()) { case "cms.webpart": mDefaultValueColumName = "WebPartDefaultValues"; before = PortalFormHelper.GetWebPartProperties(WebPartTypeEnum.Standard, PropertiesPosition.Before); after = PortalFormHelper.GetWebPartProperties(WebPartTypeEnum.Standard, PropertiesPosition.After); mDefaultSet = FormHelper.CombineFormDefinitions(before, after); WebPartInfo wi = mEditedObject as WebPartInfo; // If inherited web part load parent properties if (wi.WebPartParentID > 0) { WebPartInfo parentInfo = WebPartInfoProvider.GetWebPartInfo(wi.WebPartParentID); if (parentInfo != null) { mWebPartProperties = FormHelper.MergeFormDefinitions(parentInfo.WebPartProperties, wi.WebPartProperties); } } else { mWebPartProperties = wi.WebPartProperties; } break; case "cms.widget": before = PortalFormHelper.LoadProperties("Widget", "Before.xml"); after = PortalFormHelper.LoadProperties("Widget", "After.xml"); mDefaultSet = FormHelper.CombineFormDefinitions(before, after); mDefaultValueColumName = "WidgetDefaultValues"; WidgetInfo wii = mEditedObject as WidgetInfo; if (wii != null) { WebPartInfo wiiWp = WebPartInfoProvider.GetWebPartInfo(wii.WidgetWebPartID); if (wiiWp != null) { mWebPartProperties = FormHelper.MergeFormDefinitions(wiiWp.WebPartProperties, wii.WidgetProperties); } } break; } // Get the web part info if (mEditedObject != null) { String defVal = ValidationHelper.GetString(mEditedObject.GetValue(mDefaultValueColumName), string.Empty); mDefaultSet = LoadDefaultValuesXML(mDefaultSet); fieldEditor.Mode = FieldEditorModeEnum.SystemWebPartProperties; fieldEditor.FormDefinition = FormHelper.MergeFormDefinitions(mDefaultSet, defVal); fieldEditor.OnAfterDefinitionUpdate += fieldEditor_OnAfterDefinitionUpdate; fieldEditor.OriginalFormDefinition = mDefaultSet; fieldEditor.WebPartId = mEditedObject.Generalized.ObjectID; } ScriptHelper.HideVerticalTabs(Page); }
public bool Save(BaseInfo baseInfo, PageMode.Mode pageMode, bool saveLog, BranchInfo.BranchType branchType) { ApplyContainerInfo info = (ApplyContainerInfo)baseInfo; switch (pageMode) { case PageMode.Mode.CREATE: Insert(info); break; case PageMode.Mode.VIEW: case PageMode.Mode.TASK: case PageMode.Mode.EDIT: Update(info); break; default: break; } if (saveLog) { SaveLog(info.ModuleID, info.ApplyContainerID); } // PLM_TODO mesure data is saved return true; }
protected virtual Task <bool> ExtractMetadataAsync(ILocalFsResourceAccessor lfsra, IDictionary <Guid, IList <MediaItemAspect> > extractedAspectData, bool forceQuickMode) { if (!CanExtract(lfsra, extractedAspectData)) { return(Task.FromResult(false)); } using (var rec = new MCRecMetadataEditor(lfsra.LocalFileSystemPath)) { // Handle series information IDictionary tags = rec.GetAttributes(); // Force MimeType IList <MultipleMediaItemAspect> providerAspects; MediaItemAspect.TryGetAspects(extractedAspectData, ProviderResourceAspect.Metadata, out providerAspects); foreach (MultipleMediaItemAspect aspect in providerAspects) { aspect.SetAttribute(ProviderResourceAspect.ATTR_MIME_TYPE, "slimtv/wtv"); } MediaItemAspect.SetAttribute(extractedAspectData, MediaAspect.ATTR_ISVIRTUAL, false); MediaItemAspect.SetAttribute(extractedAspectData, VideoAspect.ATTR_ISDVD, false); string value; if (TryGet(tags, TAG_TITLE, out value) && !string.IsNullOrEmpty(value)) { MediaItemAspect.SetAttribute(extractedAspectData, MediaAspect.ATTR_TITLE, value); MediaItemAspect.SetAttribute(extractedAspectData, MediaAspect.ATTR_SORT_TITLE, BaseInfo.GetSortTitle(value)); } if (TryGet(tags, TAG_GENRE, out value)) { List <GenreInfo> genreList = new List <GenreInfo>(value.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries).Select(s => new GenreInfo { Name = s.Trim() })); IGenreConverter converter = ServiceRegistration.Get <IGenreConverter>(); foreach (var genre in genreList) { if (!genre.Id.HasValue && converter.GetGenreId(genre.Name, GenreCategory.Movie, null, out int genreId)) { genre.Id = genreId; } } foreach (GenreInfo genre in genreList) { MultipleMediaItemAspect genreAspect = MediaItemAspect.CreateAspect(extractedAspectData, GenreAspect.Metadata); genreAspect.SetAttribute(GenreAspect.ATTR_ID, genre.Id); genreAspect.SetAttribute(GenreAspect.ATTR_GENRE, genre.Name); } } if (TryGet(tags, TAG_PLOT, out value)) { MediaItemAspect.SetAttribute(extractedAspectData, VideoAspect.ATTR_STORYPLOT, value); } if (TryGet(tags, TAG_ORIGINAL_TIME, out value)) { DateTime origTime; if (DateTime.TryParse(value, out origTime)) { MediaItemAspect.SetAttribute(extractedAspectData, MediaAspect.ATTR_RECORDINGTIME, origTime); } } if (TryGet(tags, TAG_CHANNEL, out value)) { MediaItemAspect.SetAttribute(extractedAspectData, RecordingAspect.ATTR_CHANNEL, value); } long lValue; if (TryGet(tags, TAG_STARTTIME, out lValue)) { MediaItemAspect.SetAttribute(extractedAspectData, RecordingAspect.ATTR_STARTTIME, FromMCEFileTime(lValue)); } if (TryGet(tags, TAG_ENDTIME, out lValue)) { MediaItemAspect.SetAttribute(extractedAspectData, RecordingAspect.ATTR_ENDTIME, FromMCEFileTime(lValue)); } } return(Task.FromResult(true)); }
private object ExecuteGetCityNext(BaseInfo baseinfo) { if (baseinfo != null) { b = baseinfo; CityNext = new DataItem().CityNextItem(baseinfo.Id); } return null; }
public bool ChkPhoneGCM(BaseInfo baseInfo) { PhoneGCMInfo info = (PhoneGCMInfo)baseInfo; JSONInfo Info1 = new JSONInfo(); subJSONInfo Info2 = new subJSONInfo(); ArrayList al = new ArrayList(); ArrayList a2 = new ArrayList(); ArrayList a3 = new ArrayList(); //ArrayList a3 = new ArrayList(); al.Add(info.AlertRuleID); a2.Add(info.DeviceID); IDataReader reader1 = DataProvider.Instance().ChkPhoneDriverInfoDB(a2);//FMS_PhoneDriverInfo_Fetch;return CarNo,Driver if (reader1.Read()) { Info1.type = "check"; //Info1.data.CarNo = reader1.GetString(0); //Info1.data.Driver = reader1.GetString(1); Info2.CarNo = reader1.GetString(0); Info2.Driver = reader1.GetString(1); } CBO.CloseDataReader(reader1, true); a2.Clear(); a2.Add(info.AlertRuleID); IDataReader reader2 = DataProvider.Instance().ChkPhoneRuleDB(a2);//FMS_PhoneRule_Fetch;return RuleName,AlarmType,Severity if (reader2.Read()) { //Info1.data.AlertDate = info.EventTime; //Info1.data.RuleName = reader2.GetString(0); //Info1.data.AlarmType = reader2.GetString(1); //Info1.data.Severity = reader2.GetString(2); Info2.AlertDate = info.EventTime; Info2.RuleName = reader2.GetString(0); Info2.AlarmType = reader2.GetString(1); Info2.Severity = reader2.GetString(2); } CBO.CloseDataReader(reader2, true); a2.Clear(); //string output2 = JsonConvert.SerializeObject(Info2); Info1.data = new string[] { JsonConvert.SerializeObject(Info2) }; string output = JsonConvert.SerializeObject(Info1); output = output.Replace("\\", "").Replace("[\"", "[").Replace("\"]", "]"); //Info1.type = "alert"; string output1 = output.Replace("check", "alert"); al.Add(info.DeviceID); IDataReader reader = DataProvider.Instance().ChkGCMDB(al);//FMS_PhoneGCM_Fetch;return UserId,RegisterID,Phone_Mail_Logic GCMSender gcm = null; string strResultJson, strResultJson1; while (reader.Read()) { info.userID = reader.GetInt32(0).ToString(); info.RegID = reader.GetString(1); info.Phone_Mail_Logic = reader.GetString(2); gcm = new GCMSender(info.RegID , "AIzaSyAI7vpx-Q3gQ1l-2R0jH00IqnVEbaQgSR8"); strResultJson = gcm.Send(output); if (strResultJson.IndexOf("registration_id") == -1) { strResultJson1 = gcm.Send(output1); //save log record CreatePushNoticeLog(info, output1, "Google"); } else { JObject obj = (JObject)JsonConvert.DeserializeObject(strResultJson); obj = (JObject)obj["results"][0]; if (obj["registration_id"] != null) { string newRegId = obj["registration_id"].ToString(); PhoneGCMInfo newGcmInfo = new PhoneGCMInfo(); newGcmInfo.RegID = info.RegID; newGcmInfo.newRegID = newRegId; newGcmInfo.userID = info.userID; newGcmInfo.Phone_Mail_Logic = info.Phone_Mail_Logic; newGcmInfo.WorkListAlertID = info.WorkListAlertID; newGcmInfo.DeviceID = info.DeviceID; newGcmInfo.AlertRuleID = info.AlertRuleID; a3.Add(newGcmInfo); } } } if (a3.Count > 0) { for (int i = 0; i < a3.Count; i++) { PhoneGCMInfo newGcmInfo = a3[i] as PhoneGCMInfo; a2.Clear(); a2.Add(newGcmInfo.RegID); a2.Add(newGcmInfo.newRegID); a2.Add(newGcmInfo.userID); a2.Add(newGcmInfo.Phone_Mail_Logic); int reader3 = DataProvider.Instance().ChkPhoneOverRegIDDB(a2); gcm = new GCMSender(newGcmInfo.newRegID, "AIzaSyAI7vpx-Q3gQ1l-2R0jH00IqnVEbaQgSR8"); strResultJson1 = gcm.Send(output1); //save log record newGcmInfo.RegID = newGcmInfo.newRegID; CreatePushNoticeLog(info, output1, "Google"); } } CBO.CloseDataReader(reader, true); return true; }