public DefaultServerPagerLayoutOptions( bool hasPages, int pageSize, PagerMode mode, int pagesBeforeStart, int currentPage, int pagesAfterStop, string url, string skipToken, string takeToken, Type localizerType, string cssClass, Templates.Template<Templates.LayoutTemplateOptions> layoutTemplate, string operation ) :base(null, null, layoutTemplate, null, null) { HasPages = hasPages; PagesBeforeStart = pagesBeforeStart; CurrentPage = currentPage; PagesAfterStop = pagesAfterStop; Mode = mode; PageSize = pageSize; this.skipToken = skipToken; this.takeToken = takeToken; this.url = url; CssClass = cssClass; LocalizerType = localizerType; this.operation = operation; }
private int InsertUpdateTemplate() { Templates objTemp = new Templates(); if (Request.QueryString["Templateid"] != null) { objTemp.Templateid = Conversion.ParseInt(Request.QueryString["Templateid"]); } else objTemp.IsActive = true; objTemp.IsAdmin = true; objTemp.Name = txtTemplateName.Text; objTemp.OrganizationId = UserOrganizationId; string PhyImageRoot = Conversion.ParseString(ConfigurationManager.AppSettings["PhyImageRoot"]); string PhyFilesRoot = Conversion.ParseString(ConfigurationManager.AppSettings["PhyFilesRoot"]); objTemp.Body = CKEditor1.Text; objTemp.CreatedBy = currentUserInfo.UserId; objTemp.DateCreated = DateTime.Now; objTemp.TemplateTypeID = Conversion.ParseInt(ddlTemplateType.SelectedValue); if (Convert.ToInt32(ddlTemplateType.SelectedValue) == Convert.ToInt32(TemplateTypes.Invoice)) objTemp.InvoiceType = Convert.ToInt32(rdInvoiceType.SelectedValue); int result = Templates.TemplateInsertUpdate(objTemp); return result; }
/// <summary> /// This function loads the template /// </summary> /// <param name="templateId"></param> public void LoadEmailTemplate(int templateId) { var template = new Templates().GetTemplate(templateId); lblTemplateId.Text = templateId.ToString(); if (template != null) { txtTitle.Text = template.Title; lblTitle.InnerText = template.Title; txtSubject.Text = template.Subject; txtTemplateHidden.Text = template.TemplateBody; lblApplicationStatusId.Text = template.ApplicationStatusId.ToString(); if (template.TemplateTypeId == 1) { txtTitle.Visible = false; divDefaultAlert.Visible = true; lblTitle.Visible = true; } else { txtTitle.Visible = true; divDefaultAlert.Visible = false; lblTitle.Visible = false; } } }
/// <summary> /// Вызов MDIChild форрмы /// </summary> /// <param name="frm_template">MDIChild форма</param> /// <param name="mni">пункт меню</param> private void ShowMDIChild(Templates.Grid frm_template, string text, ToolStripMenuItem mni) { frm_template.MdiParent = this; frm_template.MnItem = mni; frm_template.TabText = text; frm_template.Show(dockPanel, DockState.Document); mni.Enabled = false; }
public TemplateEditor(Templates templates) { InitializeComponent(); this.templates = templates; templates.Sort((t1, t2)=>t1.name.CompareTo(t2.name)); UpdateInterface(); }
public void ProcessRequest() { HttpListenerRequest request = listener_context.Request; string raw_url = request.RawUrl; if (raw_url.IndexOf("/index") == 0 || raw_url == "/") { DisplayIndex(); return; } string id = ""; string[] data = raw_url.Split('/'); //Should load the class dynamically. IRESTCollection rest_collection; if (data[1] == "Template") { rest_collection = new Templates(listener_context); } else { (new Templates(listener_context)).CreateResponse("specfied resource is not found", 400); return; } if (data.Length > 2) { id = data[2]; } switch (request.HttpMethod.ToUpper()) { case "GET": rest_collection.ProcessGET(id); break; case "POST": using (var reader = new StreamReader(request.InputStream, request.ContentEncoding)) { var input = reader.ReadToEnd(); rest_collection.ProcessPOST(input); } break; case "PUT": using (var reader = new StreamReader(request.InputStream, request.ContentEncoding)) { var input = reader.ReadToEnd(); rest_collection.ProcessPUT(input, id); } break; case "DELETE": rest_collection.ProcessDELETE(id); break; default: rest_collection.CreateResponse("Method Not Allowed", 405); break; } }
/// <summary> /// Load email templates /// </summary> private void LoadEmailTemplates() { // load application status email templates var emailTemplates = new Templates().GetTemplates(new TemplateFilter()).ToList(); emailTemplates.Insert(0, new Template { Title = "--please select--", TemplateId = 0 }); ddlTemplates.DataSource = emailTemplates; ddlTemplates.DataValueField = "TemplateId"; ddlTemplates.DataTextField = "Title"; ddlTemplates.DataBind(); }
public FoundTemplateDesc FindTemplate(Templates templates, Template sample) { //int maxInterCorrelationShift = (int)(templateSize * maxRotateAngle / Math.PI); //maxInterCorrelationShift = Math.Min(templateSize, maxInterCorrelationShift+13); double rate = 0; double angle = 0; Complex interCorr = default(Complex); Template foundTemplate = null; int templateIndex = -1; foreach (var template in templates) { templateIndex++; // if (Math.Abs(sample.autoCorrDescriptor1 - template.autoCorrDescriptor1) > maxACFDescriptorDeviation) continue; if (Math.Abs(sample.autoCorrDescriptor2 - template.autoCorrDescriptor2) > maxACFDescriptorDeviation) continue; if (Math.Abs(sample.autoCorrDescriptor3 - template.autoCorrDescriptor3) > maxACFDescriptorDeviation) continue; if (Math.Abs(sample.autoCorrDescriptor4 - template.autoCorrDescriptor4) > maxACFDescriptorDeviation) continue; // double r = 0; if (checkACF) { r = template.autoCorr.NormDot(sample.autoCorr).Norma; if (r < minACF) continue; } if (checkICF) { interCorr = template.contour.InterCorrelation(sample.contour).FindMaxNorma(); r = interCorr.Norma / (template.contourNorma * sample.contourNorma); if (r < minICF) continue; if (Math.Abs(interCorr.Angle) > maxRotateAngle) continue; } if (template.preferredAngleNoMore90 && Math.Abs(interCorr.Angle) >= Math.PI / 2) continue;//unsuitable angle //find max rate if (r >= rate) { rate = r; foundTemplate = template; foundTemplate.index = templateIndex; angle = interCorr.Angle; } } //ignore antipatterns if (foundTemplate != null && foundTemplate.name == antiPatternName) foundTemplate = null; // if (foundTemplate != null) return new FoundTemplateDesc() { template = foundTemplate, rate = rate, sample = sample, angle = angle }; else return null; }
public string TemplatesOptions(Templates.TemplateTypes templateType) { StringBuilder sb = new StringBuilder(); TemplateController tc = new TemplateController(); sb.Append("<option value=\"0\">[RESX:Default]</option>"); List<TemplateInfo> lc = tc.Template_List(PortalId, ModuleId, templateType); foreach (TemplateInfo l in lc) { sb.Append("<option value=\"" + l.TemplateId + "\">" + l.Subject + "</option>"); } return sb.ToString(); }
private void LoadTemplate(int templateId) { Utils.GetLookUpData<DropDownList>(ref ddlTemplateType, LookUps.TemplateType); Templates objTemp = new Templates(templateId); objTemp.Templateid = templateId; txtTemplateName.Text = objTemp.Name; ddlTemplateType.SelectedValue = Conversion.ParseString(objTemp.TemplateTypeID); CKEditor1.Text = objTemp.Body; rdInvoiceType.SelectedValue = Conversion.ParseString(objTemp.InvoiceType); }
public void Launch(Vector2 targetPos, Vector2 startPos, Templates.GunOnShuttle gun) { gos=Templates.getInstance().getGunTemplate(gun.gunId); startPoint=startPos; targetPoint=new Vector2(targetPos.x+UnityEngine.Random.Range(-gos.bulletDispersion,gos.bulletDispersion),targetPos.y+UnityEngine.Random.Range(-gos.bulletDispersion,gos.bulletDispersion)); targetPoint=new Vector2(targetPoint.x-startPoint.x,targetPoint.y-startPoint.y); targetPoint/=targetPoint.magnitude; targetPoint*=gos.attackRange; targetPoint=new Vector2(targetPoint.x+startPoint.x,targetPoint.y+startPoint.y); transform.eulerAngles=new Vector3(0,GameStorage.getInstance().getAngleRelative(startPoint,targetPoint),0); setuped=true; }
/// <summary> /// Load templates /// </summary> void LoadTemplates() { var sort = Request.QueryString["sort"] ?? "createddate desc"; //bind repeater var list = new Templates().GetTemplates(new TemplateFilter { ClientId = int.Parse(lblClientId.Text) }).OrderByDescending(t => t.TemplateId); switch (sort) { case "createddate desc": list = list.OrderByDescending(t => t.TemplateId); break; case "createddate asc": list = list.OrderBy(t => t.TemplateId); break; case "title asc": list = list.OrderBy(t => t.Title); break; case "title desc": list = list.OrderByDescending(t => t.Title); break; case "folders": list = list.OrderBy(t => t.ApplicationStatus); break; } ddlSort.SelectedValue = sort; rptTemplates.DataSource = list; rptTemplates.DataBind(); //show and hide items/actions and no items if (list.Any()) { noitems.Visible = false; items.Visible = true; actions.Visible = true; } else { noitems.Visible = true; items.Visible = false; actions.Visible = false; } }
public ShowContoursForm(Templates templates, Templates samples, IImage image) { if (image == null) return; InitializeComponent(); this.templates = templates; this.samples = samples; this.samples = new Templates(); foreach (var sample in samples) this.samples.Add(sample); dgvContours.RowCount = samples.Count; SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer, true); //some magic string fileName = Path.GetTempPath() + "\\temp.bmp"; image.Save(fileName); bmp = (Bitmap)Image.FromFile(fileName); }
public void Send(Templates templateId, string to, Dictionary<string, string> data) { var template = _entities.Templates.FirstOrDefault(t => t.Id == (int)templateId); if (template == null) { return; } var message = template.Body; foreach (var item in data) { message = message.Replace(string.Format("[{0}]", item.Key.ToUpper()), item.Value); } var mail = new MailMessage(); mail.Subject = template.Subject; mail.Body = message; mail.IsBodyHtml = true; mail.To.Add(new MailAddress(to)); SendAsync(mail); }
public static void Call(Arebis.CodeGeneration.IGenerationHost host, IZetboxContext ctx, Templates.Serialization.SerializationMembersList serializationList, ObjectReferenceProperty prop, bool callGetterSetterEvents, bool updateInverseNavigator) { if (ctx == null) { throw new ArgumentNullException("ctx"); } if (prop == null) { throw new ArgumentNullException("prop"); } string name = prop.Name; string ownInterface = prop.ObjectClass.GetDataTypeString(); string referencedInterface = String.Format( "{0}.{1}", prop.GetReferencedObjectClass().Module.Namespace, prop.GetReferencedObjectClass().Name); var rel = RelationExtensions.Lookup(ctx, prop); var endRole = rel.GetEnd(prop).GetRole(); var assocNameSuffix = String.Empty; Call(host, ctx, serializationList, ownInterface, name, referencedInterface, rel, endRole, callGetterSetterEvents, updateInverseNavigator, assocNameSuffix); }
protected void rptApplicationStatuses_OnItemDataBound(object sender, RepeaterItemEventArgs e) { var appStatus = (ApplicationStatus)e.Item.DataItem; if (appStatus != null) { var ddlEmailTemplate = (DropDownList)e.Item.FindControl("ddlEmailTemplate"); ddlEmailTemplate.DataSource = templates; ddlEmailTemplate.DataTextField = "Title"; ddlEmailTemplate.DataValueField = "TemplateId"; ddlEmailTemplate.DataBind(); if (appStatus.EmailTemplateId > 0) { // Email template var emailTemplate = new Templates().GetTemplate(appStatus.EmailTemplateId); if (emailTemplate != null) { //throw new Exception(emailTemplate.TemplateId.ToString()); ddlEmailTemplate.SelectedValue = emailTemplate.TemplateId.ToString(); } } } }
internal override IFluidTemplate GetTemplate() => Templates.GetTemplate("flat");
public PagerOptions(Templates.Template<Templates.LayoutTemplateOptions> layoutTemplate, string operation = null) : base(null) { LayoutTemplate = layoutTemplate; Operation = operation; }
private static void LoadTemplatesFromDirectory(Templates parentItem, Language lang, string targetDirectory) { if (!Directory.Exists(targetDirectory)) return; string[] fileEntries = Directory.GetFiles(targetDirectory); foreach (string fileName in fileEntries) { string name = Path.GetFileNameWithoutExtension(fileName); string text = File.ReadAllText(fileName); parentItem.Set(lang, name, text); } string[] subdirectoryEntries = Directory.GetDirectories(targetDirectory); foreach (string subdirectory in subdirectoryEntries) { string name = Path.GetFileName(subdirectory); LoadTemplatesFromDirectory(parentItem.Set(lang, name).ChildItems, lang, subdirectory); } }
public void selectCampaign(Templates.CampaignInfo camp) { States.selectedLevel=-1; int i; start_but.SetActive(false); for(i=0;i<missionsContainer.transform.childCount; i++) Destroy(missionsContainer.transform.GetChild(i).gameObject); States.currentCampaign=camp; //load load campaignsMenu.SetActive(false); missionsMenu.SetActive(true); ((UnityEngine.UI.Text)descriptionPanel.GetComponentsInChildren<UnityEngine.UI.Text>()[0]).text=camp.name; ((UnityEngine.UI.Text)descriptionPanel.GetComponentsInChildren<UnityEngine.UI.Text>()[1]).text=camp.desc; int currank= PlayerPrefs.GetInt("rank"+States.currentCampaign.id+"Campaign",-1); if(currank==-1) { rank_text.GetComponent<UnityEngine.UI.Text>().text="Rank:\n"+Templates.getInstance().getRank(States.currentCampaign.defaultRank).name; rank_img.GetComponent<UnityEngine.UI.Image>().overrideSprite=Templates.getInstance().getRank(States.currentCampaign.defaultRank).img; } else { rank_text.GetComponent<UnityEngine.UI.Text>().text="Rank:\n"+Templates.getInstance().getRank(currank).name; rank_img.GetComponent<UnityEngine.UI.Image>().overrideSprite=Templates.getInstance().getRank(currank).img; } int repetitions=camp.levels.Count/2; bool free=true; int stars1,stars2=0; for(i=0;i<repetitions;i++) { stars1=PlayerPrefs.GetInt("mission"+camp.levels[i*2]+"Stars",-1); stars2=PlayerPrefs.GetInt("mission"+camp.levels[i*2+1]+"Stars",-1); GameObject tmp=(GameObject)Instantiate(Templates.getInstance().missionBlockPrefab,Vector3.zero,Quaternion.identity); selectedState=new UnityEngine.UI.SpriteState(); selectedState.disabledSprite=((UnityEngine.UI.Button)tmp.GetComponentsInChildren<UnityEngine.UI.Button>()[0]).spriteState.pressedSprite; selectedState.highlightedSprite=((UnityEngine.UI.Button)tmp.GetComponentsInChildren<UnityEngine.UI.Button>()[0]).spriteState.pressedSprite; selectedState.pressedSprite=((UnityEngine.UI.Button)tmp.GetComponentsInChildren<UnityEngine.UI.Button>()[0]).spriteState.pressedSprite; tmp.transform.SetParent(missionsContainer.transform); tmp.transform.localScale=new Vector3(1,1,1); if(stars1==-1) { if(!free) { ((UnityEngine.UI.Button)tmp.GetComponentsInChildren<UnityEngine.UI.Button>()[0]).enabled=false; ((UnityEngine.UI.Image)((UnityEngine.UI.Button)tmp.GetComponentsInChildren<UnityEngine.UI.Button>()[0]).gameObject.GetComponentsInChildren<UnityEngine.UI.Image>()[0]).overrideSprite=((UnityEngine.UI.Button)tmp.GetComponentsInChildren<UnityEngine.UI.Button>()[0]).spriteState.disabledSprite; ((UnityEngine.UI.Image)((UnityEngine.UI.Button)tmp.GetComponentsInChildren<UnityEngine.UI.Button>()[0]).gameObject.GetComponentsInChildren<UnityEngine.UI.Image>()[1]).overrideSprite = Templates.getInstance().getNumberGrey(i*2+1)[0]; ((UnityEngine.UI.Image)((UnityEngine.UI.Button)tmp.GetComponentsInChildren<UnityEngine.UI.Button>()[0]).gameObject.GetComponentsInChildren<UnityEngine.UI.Image>()[2]).overrideSprite = Templates.getInstance().getNumberGrey(i*2+1)[1]; } else { free=false; ((UnityEngine.UI.Image)((UnityEngine.UI.Button)tmp.GetComponentsInChildren<UnityEngine.UI.Button>()[0]).gameObject.GetComponentsInChildren<UnityEngine.UI.Image>()[1]).overrideSprite = Templates.getInstance().getNumber(i*2+1)[0]; ((UnityEngine.UI.Image)((UnityEngine.UI.Button)tmp.GetComponentsInChildren<UnityEngine.UI.Button>()[0]).gameObject.GetComponentsInChildren<UnityEngine.UI.Image>()[2]).overrideSprite = Templates.getInstance().getNumber(i*2+1)[1]; } } else { ((UnityEngine.UI.Image)((UnityEngine.UI.Button)tmp.GetComponentsInChildren<UnityEngine.UI.Button>()[0]).gameObject.GetComponentsInChildren<UnityEngine.UI.Image>()[1]).overrideSprite = Templates.getInstance().getNumber(i*2+1)[0]; ((UnityEngine.UI.Image)((UnityEngine.UI.Button)tmp.GetComponentsInChildren<UnityEngine.UI.Button>()[0]).gameObject.GetComponentsInChildren<UnityEngine.UI.Image>()[2]).overrideSprite = Templates.getInstance().getNumber(i*2+1)[1]; if(stars1>=1) { Color c = ((UnityEngine.UI.Button)tmp.GetComponentsInChildren<UnityEngine.UI.Button>()[0]).gameObject.transform.GetChild(3).gameObject.GetComponent<UnityEngine.UI.Image>().color; c.a=1; ((UnityEngine.UI.Button)tmp.GetComponentsInChildren<UnityEngine.UI.Button>()[0]).gameObject.transform.GetChild(3).gameObject.GetComponent<UnityEngine.UI.Image>().color=c; } if(stars1>=2) { Color c = ((UnityEngine.UI.Button)tmp.GetComponentsInChildren<UnityEngine.UI.Button>()[0]).gameObject.transform.GetChild(4).gameObject.GetComponent<UnityEngine.UI.Image>().color; c.a=1; ((UnityEngine.UI.Button)tmp.GetComponentsInChildren<UnityEngine.UI.Button>()[0]).gameObject.transform.GetChild(4).gameObject.GetComponent<UnityEngine.UI.Image>().color=c; } if(stars1>=3) { Color c = ((UnityEngine.UI.Button)tmp.GetComponentsInChildren<UnityEngine.UI.Button>()[0]).gameObject.transform.GetChild(5).gameObject.GetComponent<UnityEngine.UI.Image>().color; c.a=1; ((UnityEngine.UI.Button)tmp.GetComponentsInChildren<UnityEngine.UI.Button>()[0]).gameObject.transform.GetChild(5).gameObject.GetComponent<UnityEngine.UI.Image>().color=c; } } if(stars2==-1) { if(!free) { ((UnityEngine.UI.Button)tmp.GetComponentsInChildren<UnityEngine.UI.Button>()[1]).enabled=false; ((UnityEngine.UI.Image)((UnityEngine.UI.Button)tmp.GetComponentsInChildren<UnityEngine.UI.Button>()[1]).gameObject.GetComponentsInChildren<UnityEngine.UI.Image>()[0]).overrideSprite=((UnityEngine.UI.Button)tmp.GetComponentsInChildren<UnityEngine.UI.Button>()[1]).spriteState.disabledSprite; ((UnityEngine.UI.Image)((UnityEngine.UI.Button)tmp.GetComponentsInChildren<UnityEngine.UI.Button>()[1]).gameObject.GetComponentsInChildren<UnityEngine.UI.Image>()[1]).overrideSprite = Templates.getInstance().getNumberGrey(i*2+2)[0]; ((UnityEngine.UI.Image)((UnityEngine.UI.Button)tmp.GetComponentsInChildren<UnityEngine.UI.Button>()[1]).gameObject.GetComponentsInChildren<UnityEngine.UI.Image>()[2]).overrideSprite = Templates.getInstance().getNumberGrey(i*2+2)[1]; } else { free=false; ((UnityEngine.UI.Image)((UnityEngine.UI.Button)tmp.GetComponentsInChildren<UnityEngine.UI.Button>()[1]).gameObject.GetComponentsInChildren<UnityEngine.UI.Image>()[1]).overrideSprite = Templates.getInstance().getNumber(i*2+2)[0]; ((UnityEngine.UI.Image)((UnityEngine.UI.Button)tmp.GetComponentsInChildren<UnityEngine.UI.Button>()[1]).gameObject.GetComponentsInChildren<UnityEngine.UI.Image>()[2]).overrideSprite = Templates.getInstance().getNumber(i*2+2)[1]; } } else { ((UnityEngine.UI.Image)((UnityEngine.UI.Button)tmp.GetComponentsInChildren<UnityEngine.UI.Button>()[1]).gameObject.GetComponentsInChildren<UnityEngine.UI.Image>()[1]).overrideSprite = Templates.getInstance().getNumber(i*2+2)[0]; ((UnityEngine.UI.Image)((UnityEngine.UI.Button)tmp.GetComponentsInChildren<UnityEngine.UI.Button>()[1]).gameObject.GetComponentsInChildren<UnityEngine.UI.Image>()[2]).overrideSprite = Templates.getInstance().getNumber(i*2+2)[1]; if(stars1>=1) { Color c = ((UnityEngine.UI.Button)tmp.GetComponentsInChildren<UnityEngine.UI.Button>()[1]).gameObject.transform.GetChild(3).gameObject.GetComponent<UnityEngine.UI.Image>().color; c.a=1; ((UnityEngine.UI.Button)tmp.GetComponentsInChildren<UnityEngine.UI.Button>()[1]).gameObject.transform.GetChild(3).gameObject.GetComponent<UnityEngine.UI.Image>().color=c; } if(stars1>=2) { Color c = ((UnityEngine.UI.Button)tmp.GetComponentsInChildren<UnityEngine.UI.Button>()[1]).gameObject.transform.GetChild(4).gameObject.GetComponent<UnityEngine.UI.Image>().color; c.a=1; ((UnityEngine.UI.Button)tmp.GetComponentsInChildren<UnityEngine.UI.Button>()[1]).gameObject.transform.GetChild(4).gameObject.GetComponent<UnityEngine.UI.Image>().color=c; } if(stars1>=3) { Color c = ((UnityEngine.UI.Button)tmp.GetComponentsInChildren<UnityEngine.UI.Button>()[1]).gameObject.transform.GetChild(5).gameObject.GetComponent<UnityEngine.UI.Image>().color; c.a=1; ((UnityEngine.UI.Button)tmp.GetComponentsInChildren<UnityEngine.UI.Button>()[1]).gameObject.transform.GetChild(5).gameObject.GetComponent<UnityEngine.UI.Image>().color=c; } } GameObject block=tmp; int lev=(i*2); ((UnityEngine.UI.Button)tmp.GetComponentsInChildren<UnityEngine.UI.Button>()[0]).onClick.AddListener(() => setSelection(block,lev)); ((UnityEngine.UI.Button)tmp.GetComponentsInChildren<UnityEngine.UI.Button>()[1]).onClick.AddListener(() => setSelection(block,lev+1)); } }
// physicalApplicationPath - Pass it for locations in which HttpContext is NULL public MailTemplate(Templates file, string physicalApplicationPath = "") { switch (file) { case Templates.ApplicationError: fileNam = Templates.ApplicationError.ToString(); break; case Templates.ForgotPwd: fileNam = Templates.ForgotPwd.ToString(); break; case Templates.ClaimAssignTo: fileNam = Templates.ClaimAssignTo.ToString(); break; } XD.Load(GetEmailTemplatePath(physicalApplicationPath)); }
public GetUserProfileDialog(IConfiguration configuration) : base(nameof(GetUserProfileDialog)) { this.configuration = configuration; _templates = Templates.ParseFile(Path.Combine(".", "Dialogs", "GetUserProfileDialog", "GetUserProfileDialog.lg")); // Create instance of adaptive dialog. this._getUserProfileDialog = new AdaptiveDialog(nameof(GetUserProfileDialog)) { Recognizer = CreateCrossTrainedRecognizer(this.configuration), Generator = new TemplateEngineLanguageGenerator(_templates), Triggers = new List <OnCondition>() { // Actions to execute when this dialog begins. This dialog will attempt to fill user profile. // Each adaptive dialog can have its own recognizer. The LU definition for this dialog is under GetUserProfileDialog.lu // This dialog supports local intents. When you say things like 'why do you need my name' or 'I will not give you my name' // it uses its own recognizer to handle those. // It also demonstrates the consultation capability of adaptive dialog. When the local recognizer does not come back with // a high-confidence recognition, this dialog will defer to the parent dialog to see if it wants to handle the user input. new OnBeginDialog() { Actions = new List <Dialog>() { new SetProperties() { Assignments = new List <PropertyAssignment>() { new PropertyAssignment() { Property = "user.profile.name", // Whenever an adaptive dialog begins, any options passed in to the dialog via 'BeginDialog' are available through dialog.xxx scope. // Coalesce is a prebuilt function available as part of Adaptive Expressions. Take the first non-null value. // @EntityName is a short-hand for turn.recognized.entities.<EntityName>. Other useful short-hands are // #IntentName is a short-hand for turn.intents.<IntentName> // $PropertyName is a short-hand for dialog.<PropertyName> Value = "=coalesce(dialog.userName, @userName, @personName)" }, new PropertyAssignment() { Property = "user.profile.age", Value = "=coalesce(dialog.userAge, @age)" } } }, new TextInput() { Property = "user.profile.name", Prompt = new ActivityTemplate("${AskFirstName()}"), Validations = new List <BoolExpression>() { // Name must be 3-50 characters in length. // Validations are expressed using Adaptive expressions // You can access the current candidate value for this input via 'this.value' "count(this.value) >= 3", "count(this.value) <= 50" }, InvalidPrompt = new ActivityTemplate("${AskFirstName.Invalid()}"), // Because we have a local recognizer, we can use it to extract entities. // This enables users to say things like 'my name is vishwac' and we only take 'vishwac' as the name. Value = "=@personName", // We are going to allow any interruption for a high confidence interruption intent classification .or. // when we do not get a value for the personName entity. AllowInterruptions = "turn.recognized.score >= 0.9 || !@personName", }, new TextInput() { Property = "user.profile.age", Prompt = new ActivityTemplate("${AskUserAage()}"), Validations = new List <BoolExpression>() { // Age must be within 1-150. "int(this.value) >= 1", "int(this.value) <= 150" }, InvalidPrompt = new ActivityTemplate("${AskUserAge.Invalid()}"), UnrecognizedPrompt = new ActivityTemplate("${AskUserAge.Unrecognized()}"), // We have both a number recognizer as well as age prebuilt entity recognizer added. So take either one we get. // LUIS returns a complex type for prebuilt age entity. Take just the number value. Value = "=coalesce(@age.number, @number)", // Allow interruption if we do not get either an age or a number. AllowInterruptions = "!@age && !@number" }, new SendActivity("${ProfileReadBack()}") } }, new OnIntent() { Intent = "NoValue", // Only do this only on high confidence recognition Condition = "#NoValue.Score >= 0.9", Actions = new List <Dialog>() { new IfCondition() { Condition = "user.profile.name == null", Actions = new List <Dialog>() { new SetProperty() { Property = "user.profile.name", Value = "Human" }, new SendActivity("${NoValueForUserNameReadBack()}") }, ElseActions = new List <Dialog>() { new SetProperty() { Property = "user.profile.age", Value = "30" }, new SendActivity("${NoValueForUserAgeReadBack()}") } } } }, new OnIntent() { Intent = "GetInput", Actions = new List <Dialog>() { new SetProperties() { Assignments = new List <PropertyAssignment>() { new PropertyAssignment() { Property = "user.profile.name", Value = "=@personName" }, new PropertyAssignment() { Property = "user.profile.age", Value = "=coalesce(@age, @number)" } } } } }, new OnIntent() { Intent = "Restart", Actions = new List <Dialog>() { new DeleteProperty() { Property = "user.profile" } } }, // Help and chitchat is handled by qna new OnQnAMatch { Actions = new List <Dialog>() { new SendActivity("${@Answer}") } } } }; // Add named dialogs to the DialogSet. These names are saved in the dialog state. AddDialog(this._getUserProfileDialog); // The initial child Dialog to run. InitialDialogId = nameof(GetUserProfileDialog); }
protected override void ShowPage() { #region 临时帐号发帖 //int realuserid = -1; //bool tempaccountspost = false; //string tempusername = DNTRequest.GetString("tempusername"); //if (!Utils.StrIsNullOrEmpty(tempusername) && tempusername != username) //{ // realuserid = Users.CheckTempUserInfo(tempusername, DNTRequest.GetString("temppassword"), DNTRequest.GetInt("question", 0), DNTRequest.GetString("answer")); // if (realuserid == -1) // { // AddErrLine("临时帐号登录失败,无法继续发帖。"); // return; // } // else // { // userid = realuserid; // username = tempusername; // tempaccountspost = true; // } //} #endregion if (userid > 0) { userinfo = Users.GetShortUserInfo(userid); } #region 判断是否是灌水 AdminGroupInfo admininfo = AdminGroups.GetAdminGroupInfo(usergroupid); if (admininfo != null) { disablepost = admininfo.Disablepostctrl; } if (!UserAuthority.CheckPostTimeSpan(usergroupinfo, admininfo, oluserinfo, userinfo, ref msg)) { if (continuereply != "") { AddErrLine("<b>回帖成功</b><br />由于" + msg + "后刷新继续"); } else { AddErrLine(msg); } return; } #endregion //获取主题帖信息 PostInfo postinfo = GetPostAndTopic(admininfo); if (IsErr()) { return; } forum = Forums.GetForumInfo(forumid); smileyoff = 1 - forum.Allowsmilies; bbcodeoff = (forum.Allowbbcode == 1 && usergroupinfo.Allowcusbbcode == 1) ? 0 : 1; allowimg = forum.Allowimgcode; needaudit = UserAuthority.NeedAudit(forum, useradminid, topic, userid, disablepost, usergroupinfo); if (needaudit && topic.Displayorder == -2) { AddErrLine("主题尚未通过审核, 不能执行回复操作"); return; } #region 附件信息绑定 //得到用户可以上传的文件类型 string attachmentTypeSelect = Attachments.GetAllowAttachmentType(usergroupinfo, forum); attachextensions = Attachments.GetAttachmentTypeArray(attachmentTypeSelect); attachextensionsnosize = Attachments.GetAttachmentTypeString(attachmentTypeSelect); //得到今天允许用户上传的附件总大小(字节) int MaxTodaySize = (userid > 0 ? MaxTodaySize = Attachments.GetUploadFileSizeByuserid(userid) : 0); attachsize = usergroupinfo.Maxsizeperday - MaxTodaySize;//今天可上传得大小 //是否有上传附件的权限 canpostattach = UserAuthority.PostAttachAuthority(forum, usergroupinfo, userid, ref msg); if (canpostattach && (userinfo != null && userinfo.Uid > 0) && apb != null && config.Enablealbum == 1 && (UserGroups.GetUserGroupInfo(userinfo.Groupid).Maxspacephotosize - apb.GetPhotoSizeByUserid(userid) > 0)) { caninsertalbum = true; albumlist = apb.GetSpaceAlbumByUserId(userid); } #endregion if (!Utils.StrIsNullOrEmpty(forum.Password) && Utils.MD5(forum.Password) != ForumUtils.GetCookie("forum" + forumid + "password")) { AddErrLine("本版块被管理员设置了密码"); SetBackLink(base.ShowForumAspxRewrite(forumid, 0)); return; } #region 访问和发帖权限校验 if (!UserAuthority.VisitAuthority(forum, usergroupinfo, userid, ref msg)) { AddErrLine(msg); needlogin = true; return; } if (!UserAuthority.PostReply(forum, userid, usergroupinfo, topic)) { AddErrLine(topic.Closed == 1 ? "主题已关闭无法回复" : "您没有发表回复的权限"); needlogin = (topic.Closed == 1 ? false : true); return; } if (!UserAuthority.CheckPostTimeSpan(usergroupinfo, admininfo, oluserinfo, userinfo, ref msg)) { AddErrLine(msg); return; } #endregion // 如果是受灌水限制用户, 则判断是否是灌水 if (admininfo != null) { disablepost = admininfo.Disablepostctrl; } if (forum.Templateid > 0) { templatepath = Templates.GetTemplateItem(forum.Templateid).Directory; } AddLinkCss(BaseConfigs.GetForumPath + "templates/" + templatepath + "/editor.css", "css"); customeditbuttons = Caches.GetCustomEditButtonList(); //如果是提交... if (ispost) { string backlink = (DNTRequest.GetInt("topicid", -1) > 0 ? string.Format("postreply.aspx?topicid={0}&restore=1&forumpage=" + forumpageid, topicid) : string.Format("postreply.aspx?postid={0}&restore=1&forumpage=" + forumpageid, postid)); if (!DNTRequest.GetString("quote").Equals("")) { backlink = string.Format("{0}"e={1}", backlink, DNTRequest.GetString("quote")); } SetBackLink(backlink); #region 验证提交信息 //常规项验证 NormalValidate(admininfo, postmessage, userinfo); if (IsErr()) { return; } #endregion //是否有上传附件的权限 canpostattach = UserAuthority.PostAttachAuthority(forum, usergroupinfo, userid, ref msg); // 产生新帖子 if (!string.IsNullOrEmpty(DNTRequest.GetFormString("toreplay_user").Trim())) { postmessage = DNTRequest.GetFormString("toreplay_user").Trim() + "\n\n" + postmessage; } postinfo = CreatePostInfo(postmessage); //获取被回复帖子的作者uid int replyUserid = postid > 0 ? Posts.GetPostInfo(topicid, postid).Posterid : postinfo.Posterid; postid = postinfo.Pid; if (IsErr()) { return; } #region 当回复成功后,发送通知 if (postinfo.Pid > 0 && DNTRequest.GetString("postreplynotice") == "on") { Notices.SendPostReplyNotice(postinfo, topic, replyUserid); } #endregion //向第三方应用同步数据 Sync.Reply(postid.ToString(), topic.Tid.ToString(), topic.Title, postinfo.Poster, postinfo.Posterid.ToString(), topic.Fid.ToString(), ""); //更新主题相关信息 //UpdateTopicInfo(postmessage); #region 处理附件 //处理附件 StringBuilder sb = new StringBuilder(); AttachmentInfo[] attachmentinfo = null; string attachId = DNTRequest.GetFormString("attachid"); if (!string.IsNullOrEmpty(attachId)) { attachmentinfo = Attachments.GetNoUsedAttachmentArray(userid, attachId); Attachments.UpdateAttachment(attachmentinfo, topic.Tid, postinfo.Pid, postinfo, ref sb, userid, config, usergroupinfo); } //加入相册 if (config.Enablealbum == 1 && apb != null) { sb.Append(apb.CreateAttachment(attachmentinfo, usergroupid, userid, username)); } #endregion OnlineUsers.UpdateAction(olid, UserAction.PostReply.ActionID, forumid, forum.Name, topicid, topictitle); #region 设置提示信息和跳转链接 //辩论地址 if (topic.Special == 4) { SetUrl(Urls.ShowDebateAspxRewrite(topicid)); } else if (infloat == 0)//此处加是否弹窗提交判断是因为在IE6下弹窗提交会造成gettopicinfo, getpostlist(位于showtopic页面)被提交了两次 { SetUrl(string.Format("showtopic.aspx?forumpage={0}&topicid={1}&page=end&jump=pid#{2}", forumpageid, topicid, postid)); } if (DNTRequest.GetFormString("continuereply") == "on") { SetUrl("postreply.aspx?topicid=" + topicid + "&forumpage=" + forumpageid + "&continuereply=yes"); } if (sb.Length > 0) { UpdateUserCredits(); SetMetaRefresh(5); SetShowBackLink(true); if (infloat == 1) { AddErrLine(sb.ToString()); return; } else { AddMsgLine("<table cellspacing=\"0\" cellpadding=\"4\" border=\"0\"><tr><td colspan=2 align=\"left\"><span class=\"bold\"><nobr>发表回复成功,但图片/附件上传出现问题:</nobr></span><br /></td></tr></table>"); } } else { SetMetaRefresh(); SetShowBackLink(false); //上面已经进行用户组判断 if (postinfo.Invisible == 1) { AddMsgLine(string.Format("发表回复成功, 但需要经过审核才可以显示. {0}<br /><br />(<a href=\"" + base.ShowForumAspxRewrite(forumid, 0) + "\">点击这里返回 {1}</a>)", (DNTRequest.GetFormString("continuereply") == "on" ? "继续回复" : "返回该主题"), forum.Name)); } else { UpdateUserCredits(); MsgForward("postreply_succeed"); AddMsgLine(string.Format("发表回复成功, {0}<br />(<a href=\"" + base.ShowForumAspxRewrite(forumid, 0) + "\">点击这里返回 {1}</a>)<br />", (DNTRequest.GetFormString("continuereply") == "on" ? "继续回复" : "返回该主题"), forum.Name)); } } #endregion // 删除主题游客缓存 if (topic.Replies < (config.Ppp + 10)) { ForumUtils.DeleteTopicCacheFile(topicid); } //发送邮件通知 if (DNTRequest.GetString("emailnotify") == "on" && topic.Posterid != -1 && topic.Posterid != userid) { SendNotifyEmail(Users.GetShortUserInfo(topic.Posterid).Email.Trim(), postinfo, Utils.GetRootUrl(BaseConfigs.GetForumPath) + string.Format("showtopic.aspx?topicid={0}&page=end&jump=pid#{1}", topicid, postid)); } } }
public override void Initialize() { // Initialize service collection Services = new ServiceCollection(); Services.AddSingleton(new BotSettings()); Services.AddSingleton(new BotServices() { CognitiveModelSets = new Dictionary <string, CognitiveModelSet> { { "en-us", new CognitiveModelSet() { LuisServices = new Dictionary <string, LuisRecognizer> { { "General", new MockLuisRecognizer() }, { "Settings", new MockLuisRecognizer() }, { "SettingsName", new MockLuisRecognizer() }, { "SettingsValue", new MockLuisRecognizer() } } } } } }); Services.AddSingleton <IBotTelemetryClient, NullBotTelemetryClient>(); Services.AddSingleton(new UserState(new MemoryStorage())); Services.AddSingleton(new ConversationState(new MemoryStorage())); Services.AddSingleton(new ProactiveState(new MemoryStorage())); Services.AddSingleton(sp => { var userState = sp.GetService <UserState>(); var conversationState = sp.GetService <ConversationState>(); var proactiveState = sp.GetService <ProactiveState>(); return(new BotStateSet(userState, conversationState)); }); // Configure localized responses var localizedTemplates = new Dictionary <string, string>(); var templateFile = "ResponsesAndTexts"; var supportedLocales = new List <string>() { "en-us", "de-de", "es-es", "fr-fr", "it-it", "zh-cn" }; foreach (var locale in supportedLocales) { // LG template for en-us does not include locale in file extension. var localeTemplateFile = locale.Equals("en-us") ? Path.Combine(".", "Responses", "ResponsesAndTexts", $"{templateFile}.lg") : Path.Combine(".", "Responses", "ResponsesAndTexts", $"{templateFile}.{locale}.lg"); localizedTemplates.Add(locale, localeTemplateFile); } Services.AddSingleton(new LocaleTemplateManager(localizedTemplates, "en-us")); // Configure files for generating all responses. Response from bot should equal one of them. var allTemplates = Templates.ParseFile(Path.Combine("Responses", "ResponsesAndTexts", "ResponsesAndTexts.lg")); Services.AddSingleton(allTemplates); Services.AddSingleton <IBackgroundTaskQueue, BackgroundTaskQueue>(); Services.AddSingleton <TestAdapter, DefaultTestAdapter>(); Services.AddTransient <MainDialog>(); Services.AddTransient <VehicleSettingsDialog>(); Services.AddTransient <IBot, DefaultActivityHandler <MainDialog> >(); // Mock HttpContext for image path resolution var mockHttpContext = new DefaultHttpContext(); mockHttpContext.Request.Scheme = "http"; mockHttpContext.Request.Host = new HostString("localhost", 3980); var mockHttpContextAcessor = new HttpContextAccessor { HttpContext = mockHttpContext }; Services.AddSingleton <IHttpContextAccessor>(mockHttpContextAcessor); }
public Template GetTemplate(int startingOffset) { if (Templates.ContainsKey(startingOffset)) { return(Templates[startingOffset]); } var index = startingOffset; //verify we actually have a template sitting here if (ChunkBytes[index] != 0x0C) { //if the template list is fubar, it may still be ok! if (ChunkBytes[index - 10] != 0x0C) { return(null); } //in some cases the $(*&*&$#&*$ template offset list is full of garbage, so this is a fallback { index = startingOffset - 10; } } index += 1; //go past op code var unusedVersion = ChunkBytes[index]; index += 1; var templateId = BitConverter.ToInt32(ChunkBytes, index); index += 4; var templateOffset = BitConverter.ToInt32(ChunkBytes, index); index += 4; if (templateOffset == 0x0) { return(null); } var nextTemplateOffset = BitConverter.ToInt32(ChunkBytes, index); index += 4; var gb = new byte[16]; Buffer.BlockCopy(ChunkBytes, index, gb, 0, 16); index += 16; var g = new Guid(gb); var length = BitConverter.ToInt32(ChunkBytes, index); index += 4; var templateBytes = new byte[length]; Buffer.BlockCopy(ChunkBytes, index, templateBytes, 0, length); var br = new BinaryReader(new MemoryStream(templateBytes)); var l = LogManager.GetLogger("T"); l.Trace( $"\r\n-------------- NEW TEMPLATE at 0x{AbsoluteOffset + templateOffset - 10:X} ID: 0x{templateId:X} templateOffset: 0x{templateOffset:X} ---------------------"); //the offset + 18 gets us to the start of the actual template (0x0f 0x01, etc) return(new Template(templateId, templateOffset + 0x18, g, br, nextTemplateOffset, AbsoluteOffset + templateOffset, this)); }
public override void ExpandView(SiocCmsContext _context = null, IDbContextTransaction _transaction = null) { IsClone = true; ListSupportedCulture = GlobalLanguageService.ListSupportedCulture; this.ListSupportedCulture.ForEach(c => c.IsSupported = (Id == 0 && c.Specificulture == Specificulture) || Repository.CheckIsExists(a => a.Id == Id && a.Specificulture == c.Specificulture, _context, _transaction) ); Columns = new List <ModuleFieldViewModel>(); JArray arrField = !string.IsNullOrEmpty(Fields) ? JArray.Parse(Fields) : new JArray(); foreach (var field in arrField) { ModuleFieldViewModel thisField = new ModuleFieldViewModel() { Name = CommonHelper.ParseJsonPropertyName(field["name"].ToString()), Priority = field["priority"] != null ? field["priority"].Value <int>() : 0, DataType = (SWCmsConstants.DataType)(int) field["dataType"], Width = field["width"] != null ? field["width"].Value <int>() : 3, IsDisplay = field["isDisplay"] != null ? field["isDisplay"].Value <bool>() : true }; Columns.Add(thisField); } //Get Templates this.Templates = this.Templates ?? BETemplateViewModel.Repository.GetModelListBy( t => t.Template.Name == ActivedTemplate && t.FolderType == this.TemplateFolderType).Data; this.View = Templates.FirstOrDefault(t => !string.IsNullOrEmpty(this.Template) && this.Template.Contains(t.FileName + t.Extension)); this.View = View ?? Templates.FirstOrDefault(); if (this.View == null) { this.View = new BETemplateViewModel(new SiocTemplate() { Extension = SWCmsConstants.Parameters.TemplateExtension, TemplateId = GlobalConfigurationService.Instance.GetLocalInt(SWCmsConstants.ConfigurationKeyword.ThemeId, Specificulture, 0), TemplateName = ActivedTemplate, FolderType = TemplateFolderType, FileFolder = this.TemplateFolder, FileName = SWCmsConstants.Default.DefaultTemplate, ModifiedBy = ModifiedBy, Content = "<div></div>" }); } this.Template = SWCmsHelper.GetFullPath(new string[] { this.View?.FileFolder , this.View?.FileName }); var getDataResult = InfoModuleDataViewModel.Repository .GetModelListBy(m => m.ModuleId == Id && m.Specificulture == Specificulture , "Priority", OrderByDirection.Ascending, null, null , _context, _transaction); if (getDataResult.IsSucceed) { getDataResult.Data.JsonItems = new List <JObject>(); getDataResult.Data.Items.ForEach(d => getDataResult.Data.JsonItems.Add(d.JItem)); Data = getDataResult.Data; } var getArticles = InfoArticleViewModel.GetModelListByModule(Id, Specificulture, SWCmsConstants.Default.OrderBy, OrderByDirection.Ascending , _context: _context, _transaction: _transaction ); if (getArticles.IsSucceed) { Articles = getArticles.Data; } var getProducts = NavModuleProductViewModel.Repository.GetModelListBy( m => m.ModuleId == Id && m.Specificulture == Specificulture , SWCmsConstants.Default.OrderBy, OrderByDirection.Ascending , null, null , _context: _context, _transaction: _transaction ); if (getProducts.IsSucceed) { Products = getProducts.Data; } }
public List<TemplateInfo> Template_List(int PortalId, int ModuleId, Templates.TemplateTypes TemplateType) { return GetTemplateList(PortalId, ModuleId, TemplateType); }
public void Row_GeneratesExpectedCode() { var model = MyEntityModel(); var actual = Templates.Render("Row", model); actual = actual.Replace("\r", ""); var searchText = @" namespace MyApplication.MyModule.Entities { using Serenity; using Serenity.ComponentModel; using Serenity.Data; using Serenity.Data.Mapping; using System; using System.ComponentModel; using System.IO; [ConnectionKey(""MyConnection""), Module(""MyModule""), TableName(""my_table"")] [DisplayName(""My Table""), InstanceName(""My Table"")] [ReadPermission(""MyPermission"")] [ModifyPermission(""MyPermission"")] public sealed class MyRow : MyBaseRow, IIdRow, INameRow { [DisplayName(""My ID""), Column(""my_id""), Identity] public Int32? MyId { get { return Fields.MyId[this]; } set { Fields.MyId[this] = value; } } [DisplayName(""My Name""), Column(""my_name"")] public String MyName { get { return Fields.MyName[this]; } set { Fields.MyName[this] = value; } } [DisplayName(""My Foreign""), Column(""my_foreign_id""), ForeignKey(""my_foreign"", ""foreign_id""), LeftJoin(""jMyForeign"")] public Int32? MyForeignId { get { return Fields.MyForeignId[this]; } set { Fields.MyForeignId[this] = value; } } [DisplayName(""My Another""), Column(""my_another_id""), ForeignKey(""my_another"", ""another_id""), LeftJoin(""jMyAnother"")] public Int32? MyAnotherId { get { return Fields.MyAnotherId[this]; } set { Fields.MyAnotherId[this] = value; } } [DisplayName(""My Notes""), Column(""my_notes"")] public String MyNotes { get { return Fields.MyNotes[this]; } set { Fields.MyNotes[this] = value; } } [DisplayName(""My Foreign Name""), Expression(""jMyForeign.foreign_name"")] public String MyForeignName { get { return Fields.MyForeignName[this]; } set { Fields.MyForeignName[this] = value; } } [DisplayName(""My Foreign Value 1""), Expression(""jMyForeign.foreign_value1"")] public Decimal? MyForeignValue1 { get { return Fields.MyForeignValue1[this]; } set { Fields.MyForeignValue1[this] = value; } } [DisplayName(""My Another Name""), Expression(""jMyAnother.another_name"")] public String MyAnotherName { get { return Fields.MyAnotherName[this]; } set { Fields.MyAnotherName[this] = value; } } IIdField IIdRow.IdField { get { return Fields.MyId; } } StringField INameRow.NameField { get { return Fields.MyName; } } public static readonly RowFields Fields = new RowFields().Init(); public MyRow() : base(Fields) { } public class RowFields : MyBaseRowFields { public Int32Field MyId; public StringField MyName; public Int32Field MyForeignId; public Int32Field MyAnotherId; public StringField MyNotes; public StringField MyForeignName; public DecimalField MyForeignValue1; public StringField MyAnotherName; } } } ".Replace("\r", ""); Assert.StrictEqual(searchText, actual); }
public void Initialize() { // Initialize service collection Services = new ServiceCollection(); // Load settings var settings = new BotSettings(); Services.AddSingleton(settings); Services.AddSingleton <BotSettingsBase>(settings); // Configure telemetry Services.AddSingleton <IBotTelemetryClient, NullBotTelemetryClient>(); // Configure bot services Services.AddSingleton(new BotServices() { CognitiveModelSets = new Dictionary <string, CognitiveModelSet> { { "en-us", new CognitiveModelSet() { LuisServices = new Dictionary <string, LuisRecognizer> { { "General", new BaseMockLuisRecognizer <GeneralLuis>( new GeneralTestUtterances()) }, { "Hospitality", new BaseMockLuisRecognizer <HospitalityLuis>( new CheckOutUtterances(), new ExtendStayUtterances(), new GetReservationUtterances(), new LateCheckOutUtterances(), new RequestItemUtterances(), new RoomServiceUtterances()) } } } } } }); // Configure storage Services.AddSingleton <IStorage, MemoryStorage>(); Services.AddSingleton <UserState>(); Services.AddSingleton <ConversationState>(); Services.AddSingleton(sp => { var userState = sp.GetService <UserState>(); var conversationState = sp.GetService <ConversationState>(); return(new BotStateSet(userState, conversationState)); }); // Configure proactive Services.AddSingleton <IBackgroundTaskQueue, BackgroundTaskQueue>(); Services.AddHostedService <QueuedHostedService>(); // Configure services Services.AddSingleton <IHotelService>(new HotelService(CheckInDate)); // Configure responses Services.AddSingleton(LocaleTemplateManagerWrapper.CreateLocaleTemplateManager("en-us")); Templates = LocaleTemplateManagerWrapper.CreateTemplates(); // Register dialogs Services.AddTransient <CheckOutDialog>(); Services.AddTransient <LateCheckOutDialog>(); Services.AddTransient <ExtendStayDialog>(); Services.AddTransient <GetReservationDialog>(); Services.AddTransient <RequestItemDialog>(); Services.AddTransient <RoomServiceDialog>(); Services.AddTransient <MainDialog>(); // Configure adapters Services.AddSingleton <TestAdapter, DefaultTestAdapter>(); // Configure bot Services.AddTransient <IBot, DefaultActivityHandler <MainDialog> >(); }
public void ParseTreeTest() { var templates = Templates.ParseFile(GetExampleFilePath("ParseTreeTest.lg")); Assert.Equal(4, templates.Count); // Normal template body var normalTemplateBody = templates[0].TemplateBodyParseTree as NormalBodyContext; // - ${welcomeword} ${name} Assert.Equal("-${welcomeword} ${name}", normalTemplateBody.GetText()); var templateStrings = normalTemplateBody.normalTemplateBody().templateString(); Assert.Single(templateStrings); var expressions = templateStrings[0].normalTemplateString().expression(); Assert.Equal("${welcomeword}", expressions[0].GetText()); Assert.Equal("${name}", expressions[1].GetText()); // Condition template body var conditionalBody = templates[1].TemplateBodyParseTree as IfElseBodyContext; var rules = conditionalBody.ifElseTemplateBody().ifConditionRule(); Assert.Equal(3, rules.Length); // - IF:${a > 0} // -positive var ifCondition = rules[0].ifCondition(); Assert.Equal("-IF:${a > 0}", ifCondition.GetText()); var expressionContext = ifCondition.expression()[0]; Assert.Equal("${a > 0}", expressionContext.GetText()); //-ELSEIF: ${ a == 0} //-equals to 0 var elseIfCondition = rules[1].ifCondition(); Assert.Equal("-ELSEIF:${a == 0}", elseIfCondition.GetText()); expressionContext = elseIfCondition.expression()[0]; Assert.Equal("${a == 0}", expressionContext.GetText()); // - ELSE: // - negative var elseCondition = rules[2].ifCondition(); Assert.Equal("-ELSE:", elseCondition.GetText()); // switch/case template body var switchBody = templates[2].TemplateBodyParseTree as SwitchCaseBodyContext; var caseRules = switchBody.switchCaseTemplateBody().switchCaseRule(); Assert.Equal(4, caseRules.Length); // -SWITCH:${day} var switchStat = caseRules[0].switchCaseStat(); Assert.Equal("-SWITCH:${day}", switchStat.GetText()); expressionContext = switchStat.expression()[0]; Assert.Equal("${day}", expressionContext.GetText()); //-CASE: ${'Saturday'} //-Happy Saturday! var caseStat = caseRules[1].switchCaseStat(); Assert.Equal("-CASE:${'Saturday'}", caseStat.GetText()); expressionContext = caseStat.expression()[0]; Assert.Equal("${'Saturday'}", expressionContext.GetText()); //-DEFAULT: var defaultStat = caseRules[3].switchCaseStat(); Assert.Equal("-DEFAULT:", defaultStat.GetText()); // structure var structureBody = templates[3].TemplateBodyParseTree as StructuredBodyContext; var nameLine = structureBody.structuredTemplateBody().structuredBodyNameLine(); Assert.Equal("MyStruct", nameLine.STRUCTURE_NAME().GetText()); var bodyLines = structureBody.structuredTemplateBody().structuredBodyContentLine(); Assert.Single(bodyLines); //body =${ body} var contentLine = bodyLines[0].keyValueStructureLine(); Assert.Equal("body", contentLine.STRUCTURE_IDENTIFIER().GetText()); Assert.Single(contentLine.keyValueStructureValue()); Assert.Equal("${body}", contentLine.keyValueStructureValue()[0].expressionInStructure()[0].GetText()); }
private void InitTemplateCollection() { _templateCache = Templates.ToList(); }
/// <summary> /// /// </summary> public void Refresh() { Templates.Clear(); Load(null); LoadTreeState(); }
void Attach() { jQuery.OnDocumentReady(() => { PopulateMovies(); var templates = new Templates(); Observable.Templates( templates); jQuery.Select ( "#movieDetail" ) .On( "click", "#addLanguageBtn", evt=> { var languages = Observable.View<Movie>(evt.CurrentTarget).Data.Languages ; //. $.view( this ).data.languages; Observable.ToArrayObservable(languages).Insert( languages.Count, new Language { Name= "NewLanguage " + (counter++).ToString() }); }) .On( "click", ".close", evt=> { var view = Observable.View<Language>(evt.CurrentTarget); Observable.ToArrayObservable(view.Parent.Data).Remove(view.Index,1); // Or equivalently: $.observable( app.selectedItem.data.languages).remove( view.index, 1 ); //return false; //?? }); jQuery.Select("#addMovieBtn" ).Click(evt=> { Observable.ToArrayObservable(movies).Insert(movies.Count, new Movie { Title= "NewTitle " + counter.ToString() , Languages= new List<Language>() { new Language{Name= "German"} } }); // Set selection on the added item Select(Observable.View<Movie>("#movieList tr:last")); }); Observable.ToObjectObservable(app).Observe("SelectedItem", (evt,args)=>{ var selectedView = args.Value; if ( selectedView !=null) { LinkDetailTmpl( selectedView.Data ); } else { jQuery.Select("#movieDetail").Empty(); } }); Observable.ViewsHelpers(new {app=app, bgColor=BgColor}); LinkMovieTmpl() .On("click","tr", evt=>{ Select( Observable.View<Movie>(evt.CurrentTarget) ); }) .On("click",".close", evt=>{ Select(); var item=Observable.View<Movie>(evt.CurrentTarget); Observable.ToArrayObservable(movies).Remove( item.Index,1 ); }); jQuery.Select("#buttonShowData").Click(evt=>{ jQuery.Select( "#console" ).Append("<hr/>"); jQuery.Select( "#console" ).Append( jQuery.Select("#showData").Render(movies) ); }); jQuery.Select("#buttonDeleteLastLanguage").Click(evt=>{ if ( movies.Count>0 ) { var languages = movies[ movies.Count - 1 ].Languages; Observable.ToArrayObservable(languages ).Remove( languages.Count - 1, 1 ); } }); }); }
/// <summary> /// Method triggered by the TreeListViewDragDropBehavior Template. Takes care of moving on item in the tree, which can be from /// any level to any level /// </summary> /// <param name="destination"></param> public void MoveSelection(TreeListViewRow destination) { if (destination != null) { TemplateModel destinationItem = (destination.DataContext) as TemplateModel; try { // Setup a private collection with the selected items only. This is because the SelectedItems that are part of the view model collection // will change as soon as we start removing and adding objects TD.ObservableItemCollection <TemplateModel> selectedItems = new TD.ObservableItemCollection <TemplateModel>(); foreach (TemplateModel item in SelectedItems) { selectedItems.Add(item); } foreach (TemplateModel item in selectedItems) { // find the original parent of the object that's moved TemplateModel parentSourceItem = GetTemplate(item.Parent_ID); // If the parent is in the root level if (parentSourceItem == null) { // Remove the item in the root level Templates.Remove(item); } else { // Otherwise remove the item from the child collection parentSourceItem.ChildTemplates.Remove(item); } TreeListViewDropPosition relativeDropPosition = (TreeListViewDropPosition)destination.GetValue(RadTreeListView.DropPositionProperty); // If put on top of destination if (relativeDropPosition == TreeListViewDropPosition.Inside) { // the Parent_ID of the item will become the ID of the destination item.Parent_ID = destinationItem.ID; destinationItem.ChildTemplates.Add(item); } // If put before or after the destination else { // if the desitination is in the root collection if (destinationItem.Parent_ID == null) { // The parent_ID of the item will also be null item.Parent_ID = null; Templates.Insert(Templates.IndexOf(destinationItem), item); } else { // otherwise the Parent_ID of the item will be the same as that of the destination item item.Parent_ID = destinationItem.Parent_ID; // find the Parent of the destination item parentSourceItem = GetTemplate(destinationItem.Parent_ID); // Insert the item above the destination item in the ChildObject collection of the parent of the destination if (relativeDropPosition == TreeListViewDropPosition.Before) { parentSourceItem.ChildTemplates.Insert(parentSourceItem.ChildTemplates.IndexOf(destinationItem), item); } else { parentSourceItem.ChildTemplates.Insert(parentSourceItem.ChildTemplates.IndexOf(destinationItem) + 1, item); } } } } } catch (Exception ex) { RadWindow.Alert(ex.Message); } } }
public static Templates CreateTemplates() { return(Templates.ParseFile(Path.Join(@"Responses\ResponsesAndTexts", $"ResponsesAndTexts.lg"))); }
public void TestStructuredTemplate() { var templates = Templates.ParseFile(GetExampleFilePath("StructuredTemplate.lg")); var evaled = templates.Evaluate("AskForAge.prompt"); Assert.IsTrue( JToken.DeepEquals(JObject.Parse("{\"lgType\":\"Activity\",\"text\":\"how old are you?\",\"speak\":\"how old are you?\"}"), evaled as JObject) || JToken.DeepEquals(JObject.Parse("{\"lgType\":\"Activity\",\"text\":\"what's your age?\",\"speak\":\"what's your age?\"}"), evaled as JObject)); evaled = templates.Evaluate("AskForAge.prompt2"); Assert.IsTrue( JToken.DeepEquals(JObject.Parse("{\"lgType\":\"Activity\",\"text\":\"how old are you?\",\"suggestedactions\":[\"10\",\"20\",\"30\"]}"), evaled as JObject) || JToken.DeepEquals(JObject.Parse("{\"lgType\":\"Activity\",\"text\":\"what's your age?\",\"suggestedactions\":[\"10\",\"20\",\"30\"]}"), evaled as JObject)); evaled = templates.Evaluate("AskForAge.prompt3"); Assert.IsTrue( JToken.DeepEquals(JObject.Parse("{\"lgType\":\"Activity\",\"text\":\"${GetAge()}\",\"suggestions\":[\"10 | cards\",\"20 | cards\"]}"), evaled as JObject)); evaled = templates.Evaluate("T1"); Assert.IsTrue( JToken.DeepEquals(JObject.Parse("{\"lgType\":\"Activity\",\"text\":\"This is awesome\",\"speak\":\"foo bar I can also speak!\"}"), evaled as JObject)); evaled = templates.Evaluate("ST1"); Assert.IsTrue( JToken.DeepEquals(JObject.Parse("{\"lgType\":\"MyStruct\",\"text\":\"foo\",\"speak\":\"bar\"}"), evaled as JObject)); evaled = templates.Evaluate("AskForColor"); Assert.IsTrue( JToken.DeepEquals(JObject.Parse("{\"lgType\":\"Activity\",\"suggestedactions\":[{\"lgType\":\"MyStruct\",\"speak\":\"bar\",\"text\":\"zoo\"},{\"lgType\":\"Activity\",\"speak\":\"I can also speak!\"}]}"), evaled as JObject)); evaled = templates.Evaluate("MultiExpression"); var options = new string[] { "{\r\n \"lgType\": \"Activity\",\r\n \"speak\": \"I can also speak!\"\r\n} {\r\n \"lgType\": \"MyStruct\",\r\n \"text\": \"hi\"\r\n}", "{\n \"lgType\": \"Activity\",\n \"speak\": \"I can also speak!\"\n} {\n \"lgType\": \"MyStruct\",\n \"text\": \"hi\"\n}" }; Assert.IsTrue(options.Contains(evaled.ToString())); evaled = templates.Evaluate("StructuredTemplateRef"); Assert.IsTrue( JToken.DeepEquals(JObject.Parse("{\"lgType\":\"MyStruct\",\"text\":\"hi\"}"), evaled as JObject)); evaled = templates.Evaluate("MultiStructuredRef"); Assert.IsTrue( JToken.DeepEquals(JObject.Parse("{\"lgType\":\"MyStruct\",\"list\":[{\"lgType\":\"SubStruct\",\"text\":\"hello\"},{\"lgType\":\"SubStruct\",\"text\":\"world\"}]}"), evaled as JObject)); evaled = templates.Evaluate("templateWithSquareBrackets", new { manufacturer = new { Name = "Acme Co" } }); Assert.IsTrue( JToken.DeepEquals(JObject.Parse("{\"lgType\":\"Struct\",\"text\":\"Acme Co\"}"), evaled as JObject)); evaled = templates.Evaluate("ValueWithEqualsMark", new { name = "Jack" }); Assert.IsTrue( JToken.DeepEquals(JObject.Parse("{\"lgType\": \"Activity\",\"text\": \"Hello! welcome back. I have your name = Jack\"}"), evaled as JObject)); }
void InitTemplateCollection() { cache = Templates?.ToDictionary(x => x.Name) ?? new Dictionary <string, NamedTemplate>(); }
void OnDestroy() { if (!IsTemplate) { templates = null; return ; } //if FindTemplates never called than TemplateName==null if (TemplateName!=null) { Templates.Delete(TemplateName); } }
private void AddTemplateItemsRecursive(ToolStripMenuItem menuItem, Templates templates) { foreach (TemplateItem templateItem in templates) { ToolStripItem item = HMS.SetTemplateMenuItem(menuItem, templateItem.Name, templateItem.Text); if (templateItem.Submenu) { AddTemplateItemsRecursive((ToolStripMenuItem)item, templateItem.ChildItems); } else { item.Click += (o, a) => { var toolStripItem = o as ToolStripItem; if (toolStripItem != null) InsertTemplate(toolStripItem.AccessibleDescription); }; } // if } // foreach }
protected void gvTemplates_OnRowDeleting(object sender, GridViewDeleteEventArgs e) { Templates.RemoveTemplate((string)gvTemplates.DataKeys[e.RowIndex][0]); DataBind(); }
internal override IFluidTemplate GetTemplate() => Templates.GetTemplate("plastic");
public void Save(ICloseable window) { var startKw = StartEvent.Kw; var startDatum = Core.Helper.CalculateWeek(StartEvent.Kw); var zielKw = Helper.CalculateWeek(ZielDatum); StartEvent.Kw = zielKw; var sendMail = false; var mails = new InfoAnRednerUndKoordinatorWindow(); var mailsData = (InfoAnRednerUndKoordinatorViewModel)mails.DataContext; mailsData.DisableCancelButton(); //MAIL WEGEN STARTBUCHUNG if (StartEvent.Status == EventStatus.Zugesagt) { var ev = (StartEvent as Invitation); if (ev.Ältester.Versammlung == DataContainer.MeineVersammlung) { mailsData.InfoAnKoordinatorTitel = "Info an Redner"; mailsData.MailTextKoordinator = Templates.GetMailTextEreignisTauschenAnRedner(ev.Ältester, startDatum, ZielDatum, ev.Vortrag.Vortrag.ToString(), ev.Ältester.Versammlung.Name); } else { mailsData.InfoAnKoordinatorTitel = "Info an Koordinator"; mailsData.MailTextKoordinator = Templates.GetMailTextEreignisTauschenAnKoordinator(ev.Ältester.Versammlung, startDatum, ZielDatum, ev.Ältester.Name, ev.Vortrag.Vortrag.ToString(), ev.Ältester.Versammlung.Name); } sendMail = true; } string startBuchungInfo = string.Empty; //MAIL & TODO WEGEN ZIELBUCHUNG if (ZielBuchungBelegt) { var headerText = string.Empty; if (ZielbuchungTauschenChecked) { if (ZielEvent.Status == EventStatus.Anfrage) { var ev = (ZielEvent as Inquiry); ev.Kws.Remove(zielKw); ev.Kws.Add(startKw); } else if (ZielEvent.Status == EventStatus.Ereignis) { ZielEvent.Kw = startKw; } else { ZielEvent.Kw = startKw; var ev = (ZielEvent as Invitation); if (ev.Ältester.Versammlung == DataContainer.MeineVersammlung) { mailsData.InfoAnRednerTitel = "Info an Redner"; mailsData.MailTextRedner = Templates.GetMailTextEreignisTauschenAnRedner(ev.Ältester, ZielDatum, startDatum, ev.Vortrag.Vortrag.ToString(), ev.Ältester.Versammlung.Name); } else { mailsData.InfoAnRednerTitel = "Info an Koordinator"; mailsData.MailTextRedner = Templates.GetMailTextEreignisTauschenAnKoordinator(ev.Ältester.Versammlung, ZielDatum, startDatum, ev.Ältester.Name, ev.Vortrag.Vortrag.ToString(), ev.Ältester.Versammlung.Name); } sendMail = true; } startBuchungInfo = "Die Buchung am neuen Datum wurde mit dem bisherigen Datum getauscht."; headerText = "Diese Buchung wurde verschoben"; } else if (ZielbuchungLöschenChecked) { switch (ZielEvent.Status) { case EventStatus.Anfrage: var ev = (ZielEvent as Inquiry); ev.Kws.Remove(zielKw); if (ev.Kws.Count == 0) { DataContainer.OffeneAnfragen.Remove(ev); } //ToDo: Info an Versammlung über doppelbuchung der Anfrage?? break; case EventStatus.Zugesagt: var inv = (ZielEvent as Invitation); if (inv.Ältester.Versammlung == DataContainer.MeineVersammlung) { mailsData.InfoAnRednerTitel = "Info an Redner"; mailsData.MailTextRedner = Templates.GetMailTextAblehnenRedner(inv); } else { mailsData.InfoAnRednerTitel = "Info an Koordinator"; mailsData.MailTextRedner = Templates.GetMailTextAblehnenKoordinator(inv); } DataContainer.Absagen.Add(new Cancelation(zielKw, inv.Ältester, EventStatus.Zugesagt)); DataContainer.MeinPlanRemove(inv); sendMail = true; break; case EventStatus.Ereignis: DataContainer.MeinPlanRemove(ZielEvent); break; default: break; } startBuchungInfo = "Die Buchung am neuen Datum wurde gelöscht."; headerText = "Diese Buchung wurde gelöscht"; } ActivityLog.AddActivity.BuchungVerschieben(ZielEvent, mailsData.MailTextRedner, ZielDatum, "Eine andere Buchung wurde auf das bisherige Datum verschoben.", headerText); } else { startBuchungInfo = "Das neue Datum war in der Planung offen."; } if (sendMail) { mails.ShowDialog(); } DataContainer.UpdateTalkDate(StartEvent?.Vortrag?.Vortrag); DataContainer.UpdateTalkDate(ZielEvent?.Vortrag?.Vortrag); ActivityLog.AddActivity.BuchungVerschieben(StartEvent, mailsData.MailTextKoordinator, startDatum, startBuchungInfo, "Buchung wurde verschoben"); // Event1 //Event2 Speichern = true; window?.Close(); }
private static void AddTemplatesFromIni(Templates parentItem, Language lang, INI ini) { string langString = lang.ToString(); foreach (string section in ini.Dict.Keys) { if (!section.StartsWith(langString)) continue; string name = section.Substring(langString.Length + 1).Trim(); string text = ini.GetSectionText(section); parentItem.Set(lang, name, text); } }
void InitTemplateCollection() { templateCache = Templates?.ToDictionary(x => x.DataType) ?? new Dictionary <Type, TypeTemplate>(); }
private void SetTemplateContent(Templates templateItem) { switch (templateItem.Template_UserControlName) { case "TBeforeAfter": //if (tBA == null) //{ // tBA = new TBeforeAfter(Agencys, Patients, templateItem, TemplateImportDate); //} tBA = new TBeforeAfter(Agencys, Patients, templateItem, TemplateImportDate); TemplateContent = tBA; break; case "TIn6s": //if (tI6 == null) //{ // tI6 = new TIn6s(Agencys, Patients, templateItem, TemplateImportDate); //} tI6 = new TIn6s(Agencys, Patients, templateItem, TemplateImportDate); TemplateContent = tI6; break; case "TInOut9s": //if (tIO9 == null) //{ // tIO9 = new TInOut9s(Agencys, Patients, templateItem, TemplateImportDate); //} tIO9 = new TInOut9s(Agencys, Patients, templateItem, TemplateImportDate); TemplateContent = tIO9; break; case "TInOut10s": //if (tIO10 == null) //{ // tIO10 = new TInOut10s(Agencys, Patients, templateItem, TemplateImportDate); //} tIO10 = new TInOut10s(Agencys, Patients, templateItem, TemplateImportDate); TemplateContent = tIO10; break; case "TInOut11s": //if (tIO11 == null) //{ // tIO11 = new TInOut11s(Agencys, Patients, templateItem, TemplateImportDate); //} tIO11 = new TInOut11s(Agencys, Patients, templateItem, TemplateImportDate); TemplateContent = tIO11; break; case "TXRay6s": //if (tXR6 == null) //{ // tXR6 = new TXRay6s(Agencys, Patients, templateItem, TemplateImportDate); //} tXR6 = new TXRay6s(Agencys, Patients, templateItem, TemplateImportDate); TemplateContent = tXR6; break; case "TXRay19s": //if (tXR19 == null) //{ // tXR19 = new TXRay19s(Agencys, Patients, templateItem, TemplateImportDate); //} tXR19 = new TXRay19s(Agencys, Patients, templateItem, TemplateImportDate); TemplateContent = tXR19; break; case "TPlasterModel5s": //if (tPM15 == null) //{ // tPM15 = new TPlasterModel5s(Agencys, Patients, templateItem, TemplateImportDate); //} tPM15 = new TPlasterModel5s(Agencys, Patients, templateItem, TemplateImportDate); TemplateContent = tPM15; break; case "TFdi52s": //if (tF52 == null) //{ // tF52 = new TFdi52s(Agencys, Patients, templateItem, TemplateImportDate); //} tF52 = new TFdi52s(Agencys, Patients, templateItem, TemplateImportDate); TemplateContent = tF52; break; case "TOthers1s": //if (tO1 == null) //{ // tO1 = new TOthers1s(Agencys, Patients, templateItem, TemplateImportDate); //} tO1 = new TOthers1s(Agencys, Patients, templateItem, TemplateImportDate); TemplateContent = tO1; break; } using (var dde = new DigiDentalEntities()) { var queryImportDate = from ti in dde.TemplateImages where ti.Patient_ID == Patients.Patient_ID && ti.Template_ID == TemplateItem.Template_ID group ti by ti.TemplateImage_ImportDate into tt select tt.Key.ToString(); ImportDateCollect = queryImportDate.ToList(); //ImportDateCollect = new ObservableCollection<string>(queryImportDate); } }
public override void WriteInitializationScript(System.IO.TextWriter writer) { var options = new Dictionary <string, object>(Events); var positionOptions = new Dictionary <string, object>(); if (Position.Bottom != 20) { positionOptions.Add("bottom", Position.Bottom); } if (Position.Right != 20) { positionOptions.Add("right", Position.Right); } if (Position.Top != int.MinValue) { positionOptions.Add("top", Position.Top); } if (Position.Left != int.MinValue) { positionOptions.Add("left", Position.Left); } if (!Position.Pinned) { positionOptions.Add("pinned", Position.Pinned); } if (positionOptions.Count > 0) { options.Add("position", positionOptions); } if (Stacking != NotificationStackingSettings.Default) { options["stacking"] = Stacking; } if (!HideOnClick) { options["hideOnClick"] = HideOnClick; } if (Button) { options["button"] = Button; } if (AllowHideAfter > 0) { options["allowHideAfter"] = AllowHideAfter; } if (AutoHideAfter != 5000) { options["autoHideAfter"] = AutoHideAfter; } if (AppendTo.HasValue()) { options["appendTo"] = AppendTo; } if (Width.HasValue()) { options["width"] = Width; } if (Height.HasValue()) { options["height"] = Height; } var animation = Animation.ToJson(); if (animation.Any()) { if (animation["animation"] is bool) { options["animation"] = false; } else { options["animation"] = animation["animation"]; } } if (Templates.Any()) { options["templates"] = Templates.Select(t => t.Serialize()); } writer.Write(Initializer.Initialize(Selector, "Notification", options)); base.WriteInitializationScript(writer); }
protected void LoadPopInfobyTemplateId(int templateId) { Templates objTemp = new Templates(templateId); lblTemplateID.Text = objTemp.Templateid.ToString(); lblTemplateName.Text = objTemp.Name; lblTemplateDate.Text = objTemp.DateCreated.ToShortDateString(); if (objTemp.InvoiceType == 1) lblInvoiceType.Text = InvoiceType.Single.ToString(); else lblInvoiceType.Text = InvoiceType.Commulative.ToString(); lblTemplateType.Text = objTemp.TemplateType; ltrBody.Text = objTemp.Body; }
public static Templates getInstance() { if(instance==null) instance=new Templates(); return instance; }
public static Templates aggiungiOggettoCustomTemplateFasc(OggettoCustom oggettoCustom, Templates template, Page page) { try { return(docsPaWS.aggiungiOggettoCustomTemplateFasc(oggettoCustom, template)); } catch (Exception ex) { ErrorManager.redirect(page, ex); return(null); } }
public void LoadLevel(Templates.LevelInfo lv, bool clearTries) { totalHp=0; curHp=0; curLevel=lv.num; if(clearTries) tries=0; else tries++; fadeOut(0.25f); Application.LoadLevel(lv.file); if(cam!=null) cam.GetComponent<CameraBehaviour>().loadTileGo(); }
public void pauseButtonCallback() { States.inPauseMenu = true; mainPanel.SetActive(false); pausePanel.SetActive(true); missionNameLabel.GetComponent <UnityEngine.UI.Text>().text = "Mission " + (States.selectedLevel + 1) + ": " + Templates.getInstance().getLevel((int)States.currentCampaign.levels[States.selectedLevel]).levelName; missionDescLabel.GetComponent <UnityEngine.UI.Text>().text = Templates.getInstance().getLevel((int)States.currentCampaign.levels[States.selectedLevel]).description; }
public static string ImprimBL(string OTID, string DetailID, bool ReplaceOnly = false) { string pathSave = ""; pathSave = Globale_Varriables.VAR.PATH_STOCKAGE + OTID + @"\BL\"; var directory = new DirectoryInfo(pathSave); if (!Directory.Exists(pathSave)) { try { Directory.CreateDirectory(pathSave); } catch (Exception exp) { Configs.Debug(exp, "maintenance.Controllers.AjoindreController.ajChargerFichier", "Impossible de créer un dossier Upload, chemin : " + pathSave); } } /********************************************* code generate pdf *********************************************/ try { Templates temp = new Templates(); DataRow rTemplate = temp.getTemplateService(DetailID); string contents = ""; string articles = ""; string proc = ""; string user = "******"; string _fileName = DetailID + "_BON_LIVRAISON.pdf"; if (rTemplate != null) { contents = rTemplate["html"].ToString(); articles = rTemplate["articles"].ToString(); proc = rTemplate["proc_datasource"].ToString(); } if (proc != "no") { pathSave = pathSave + _fileName; DataTable dt = Configs._query.executeProc(proc, "OTID@int@" + OTID + "#DetailID@int@" + DetailID); if (dt != null && dt.Rows.Count > 0) { contents = temp.getGeneratedTemp(dt, contents, user); if (articles.Length > 4) { var match = Regex.Match(contents, @"{FOR ([A-Z][a-z]+)}"); var match1 = Regex.Match(contents, @"{/FOR ([A-Z][a-z]+)}"); if (match.Success && match1.Success) { dt = Configs._query.executeSql(articles.Replace("SID", DetailID)); if (dt != null && dt.Rows.Count > 0) { int bIndex = match.Index; string _obj = match.Value; _obj = _obj.Substring(_obj.IndexOf(" ") + 1); _obj = _obj.Substring(0, _obj.Length - 1); int blmatch = match.Value.Length; int eIndex = match1.Index; int elmatch = match1.Value.Length; int lStr = eIndex - (bIndex + blmatch); string fStr = contents.Substring(bIndex + blmatch, lStr); string lines = ""; for (int i = 0; i < dt.Rows.Count; i++) { string line = fStr; lines += temp.getGeneratedRowTemp(dt.Rows[i], line, user, i, _obj + "."); } contents = contents.Substring(0, bIndex) + lines + contents.Substring(eIndex + elmatch); contents = contents.Replace("{TAB_Start}", "").Replace("{/TAB_Start}", ""); } else { match = Regex.Match(contents, @"{TAB_Start}"); match1 = Regex.Match(contents, @"{/TAB_Start}"); if (match.Index > 0 && match1.Index > match.Index) { contents = contents.Substring(0, match.Index - 1) + contents.Substring(match1.Index + "{/TAB_Start}".Length); } } } } } } contents = contents.Replace("{url_server}", Globale_Varriables.VAR.get_URL_HREF()); if (ReplaceOnly && !File.Exists(pathSave)) { return(null); } temp.GeneratedPDF(pathSave, contents); string urlRedirection = Globale_Varriables.VAR.urlFileUpload + "/" + OTID + "/BL/" + _fileName; return(urlRedirection); } catch (Exception) { } /********************************************* code generate pdf *********************************************/ return(null); }
public GameObject getFriendlyInFireZone(GameObject enemyShuttle, Templates.GunOnShuttle gun) { GameObject ret = null; float dist=0; float mindist=-1; Templates.GunTemplate gunTemp = Templates.getInstance().getGunTemplate(gun.gunId); Vector2 gunPos = new Vector2(enemyShuttle.transform.position.x+gun.pos.x,enemyShuttle.transform.position.z+gun.pos.y); float gunAngle = Mathf.Repeat(enemyShuttle.GetComponent<EnemyShuttleBehaviour>().getAngle()+gun.turnAngle,360); Vector2 pos2; foreach(GameObject friendly in getFriendlyShuttles()) { pos2=new Vector2(friendly.transform.position.x,friendly.transform.position.z); if((dist=Vector2.Distance(gunPos,pos2))<=gunTemp.attackRange && Mathf.Abs(getAngleDst(gunAngle,getAngleRelative(enemyShuttle,friendly)))<=gunTemp.attackAngle) { if(mindist<0) { ret=friendly; mindist=dist; } else { if(dist<mindist) { ret=friendly; mindist=dist; } } } } return ret; }
private Templates GetTemplates(string fileName) { var filePath = GetExceptionExampleFilePath(fileName); return(Templates.ParseFile(filePath)); }
private IList <Diagnostic> GetDiagnostics(string fileName) { var filePath = GetExceptionExampleFilePath(fileName); return(Templates.ParseFile(filePath).Diagnostics); }
public void UpdatePACFromChnDomainsAndIP(Configuration config, Templates template) { if (SS_template == null) { lastConfig = config; lastTemplate = template; var http = new WebClient(); http.Headers.Add(@"User-Agent", string.IsNullOrEmpty(config.proxyUserAgent) ? USER_AGENT : config.proxyUserAgent); var proxy = new WebProxy(IPAddress.Loopback.ToString(), config.localPort); if (!string.IsNullOrEmpty(config.authPass)) { proxy.Credentials = new NetworkCredential(config.authUser, config.authPass); } http.Proxy = proxy; http.DownloadStringCompleted += HttpDownloadSSCNIPTemplateCompleted; switch (template) { case Templates.ss_white: TEMPLATE_URL = SS_WHITE_TEMPLATE_URL; break; case Templates.ss_white_r: TEMPLATE_URL = SS_WHITER_TEMPLATE_URL; break; case Templates.ss_cnip: TEMPLATE_URL = SS_CNIP_TEMPLATE_URL; break; default: throw new ArgumentOutOfRangeException(nameof(template), template, null); } http.DownloadStringAsync(new Uri(TEMPLATE_URL + @"?rnd=" + Utils.RandUInt32())); } else if (cnIpRange == null || cnIp16Range == null) { var http = new WebClient(); http.Headers.Add(@"User-Agent", string.IsNullOrEmpty(config.proxyUserAgent) ? USER_AGENT : config.proxyUserAgent); var proxy = new WebProxy(IPAddress.Loopback.ToString(), config.localPort); if (!string.IsNullOrEmpty(config.authPass)) { proxy.Credentials = new NetworkCredential(config.authUser, config.authPass); } http.Proxy = proxy; http.DownloadStringCompleted += HttpDownloadCNIPCompleted; http.DownloadStringAsync(new Uri(CNIP_URL + @"?rnd=" + Utils.RandUInt32())); } else { var http = new WebClient(); http.Headers.Add(@"User-Agent", string.IsNullOrEmpty(config.proxyUserAgent) ? USER_AGENT : config.proxyUserAgent); var proxy = new WebProxy(IPAddress.Loopback.ToString(), config.localPort); if (!string.IsNullOrEmpty(config.authPass)) { proxy.Credentials = new NetworkCredential(config.authUser, config.authPass); } http.Proxy = proxy; http.DownloadStringCompleted += HttpDownloadDomainsCompleted; http.DownloadStringAsync(new Uri(CNDOMAINS_URL + @"?rnd=" + Utils.RandUInt32())); } }
/// <summary> /// Method to load themes in the left panel /// </summary> private void LoadThemes() { try { StateManager stateManager = StateManager.Instance; MiscellaneousController objMisc = new MiscellaneousController(); string strPath = ""; if (Request.RawUrl.Contains("/")) { strPath = Request.RawUrl.ToString().Substring(0, Request.RawUrl.ToString().LastIndexOf('/')); strPath = strPath.Substring(strPath.LastIndexOf('/') + 1); } if ((strPath != "") && (Request.QueryString["Type"] != null)) { objTribute.TributeUrl = strPath; objTribute.TypeDescription = Request.QueryString["Type"].ToString().ToLower().Replace("newbaby", "new baby"); objTribute = objMisc.GetTributeSessionForUrlAndType(objTribute, WebConfig.ApplicationType.ToString()); } if (objTribute != null) { if (objTribute.TributeId > 0) { _tributeId = objTribute.TributeId; _tributeName = objTribute.TributeName; _tributeType = objTribute.TypeDescription; _tributeUrl = objTribute.TributeUrl; } } Templates objTributeType = new Templates(); objTributeType.TributeType = _tributeType; // "Wedding"; int existingTheme = GetExistingTheme().TemplateID; MiscellaneousController _controller = new MiscellaneousController(); List<Templates> lstThemes = _controller.GetThemesFolderList(objTributeType, WebConfig.ApplicationType); StringBuilder sbChangeSiteTheme = new StringBuilder(); foreach (Templates objThemes in lstThemes) { sbChangeSiteTheme.Append("<div class='yt-Form-Field yt-Form-Field-Radio' id='" + objThemes.ThemeCssClass + "'>"); // + objThemes.TemplateName.Remove(objThemes.TemplateName.IndexOf(" "), 1) + "'>"); sbChangeSiteTheme.Append("<input name='rdoTheme' type='radio' runat='server' id='rdo" + objThemes.TemplateID + "' onclick='javascript:Themer(\"" + objThemes.ThemeValue + "\");GetSelectedTheme(" + objThemes.TemplateID + ",\"" + objThemes.ThemeValue + "\");' value='" + objThemes.ThemeValue + "'"); string appPath = string.Empty; if (WebConfig.ApplicationMode.ToLower().Equals("local")) { appPath = WebConfig.AppBaseDomain; } else { appPath = string.Format("{0}{1}{2}", "http://www.", WebConfig.TopLevelDomain, "/"); } if (hdnSelectedTheme.Value != string.Empty) { if (int.Parse(hdnSelectedTheme.Value) == objThemes.TemplateID) { sbChangeSiteTheme.Append(" Checked='Checked' />"); idSheet.Href = appPath + "assets/themes/" + objThemes.FolderName + "/theme.css"; //to set the selected theme } else sbChangeSiteTheme.Append(" />"); } else { if (existingTheme == objThemes.TemplateID) { sbChangeSiteTheme.Append(" Checked='Checked' />"); idSheet.Href = appPath + "assets/themes/" + objThemes.FolderName + "/theme.css"; //to set the selected theme } else sbChangeSiteTheme.Append(" />"); } sbChangeSiteTheme.Append("<label for='rdo" + objThemes.TemplateID + "'>"); //rdo" + objThemes.TemplateName + "'>"); sbChangeSiteTheme.Append(objThemes.TemplateName + " <span class='yt-ThemeColorPrimary'></span><span class='yt-ThemeColorSecondary'></span></label>"); sbChangeSiteTheme.Append("</div>"); } litThemes.Text = sbChangeSiteTheme.ToString(); stateManager.Add("ThemeOnMaster", lstThemes, StateManager.State.Session); } catch (Exception ex) { throw ex; } }
// Start is called before the first frame update void Start() { templates = GameObject.FindGameObjectWithTag("Templates").GetComponent <Templates>(); templates.rooms.Add(this.gameObject); }
public override void ExpandView(SiocCmsContext _context = null, IDbContextTransaction _transaction = null) { ListSupportedCulture = GlobalLanguageService.ListSupportedCulture; StrNormalPrice = SwCmsHelper.FormatPrice(NormalPrice); StrDealPrice = SwCmsHelper.FormatPrice(DealPrice); StrImportPrice = SwCmsHelper.FormatPrice(ImportPrice); //if (!string.IsNullOrEmpty(this.Tags)) //{ // ListTag = JArray.Parse(this.Tags); //} Properties = new List <ExtraProperty>(); if (!string.IsNullOrEmpty(ExtraProperties)) { JArray arr = JArray.Parse(ExtraProperties); foreach (JToken item in arr) { Properties.Add(item.ToObject <ExtraProperty>()); } } //Get Templates this.Templates = this.Templates ?? BETemplateViewModel.Repository.GetModelListBy( t => t.Template.Name == ActivedTemplate && t.FolderType == this.TemplateFolderType).Data; if (!string.IsNullOrEmpty(Template)) { this.View = Templates.FirstOrDefault(t => Template.Contains(t.FileName)); } this.View = View ?? Templates.FirstOrDefault(); if (this.View == null) { this.View = new BETemplateViewModel(new SiocTemplate() { Extension = SWCmsConstants.Parameters.TemplateExtension, TemplateId = GlobalConfigurationService.Instance.GetLocalInt(SWCmsConstants.ConfigurationKeyword.ThemeId, Specificulture, 0), TemplateName = ActivedTemplate, FolderType = TemplateFolderType, FileFolder = this.TemplateFolder, FileName = SWCmsConstants.Default.DefaultTemplate, ModifiedBy = ModifiedBy, Content = "<div></div>" }); } this.Template = SwCmsHelper.GetFullPath(new string[] { this.View?.FileFolder , this.View?.FileName }); var getCateArticle = CommonRepository.Instance.GetCategoryArticleNav(Id, Specificulture, _context, _transaction); if (getCateArticle.IsSucceed) { this.Categories = getCateArticle.Data; this.Categories.ForEach(c => { c.IsActived = NavCategoryArticleViewModel.Repository.CheckIsExists(n => n.CategoryId == c.CategoryId && n.ArticleId == Id, _context, _transaction); }); } var getModuleArticle = CommonRepository.Instance.GetModuleArticleNav(Id, Specificulture, _context, _transaction); if (getModuleArticle.IsSucceed) { this.Modules = getModuleArticle.Data; } var getArticleModule = CommonRepository.Instance.GetArticleModuleNav(Id, Specificulture, _context, _transaction); if (getArticleModule.IsSucceed) { this.ModuleNavs = getArticleModule.Data; } var getArticleMedia = NavArticleMediaViewModel.Repository.GetModelListBy(n => n.ArticleId == Id && n.Specificulture == Specificulture, _context, _transaction); if (getArticleMedia.IsSucceed) { MediaNavs = getArticleMedia.Data.OrderBy(p => p.Priority).ToList(); MediaNavs.ForEach(n => n.IsActived = true); } this.ListSupportedCulture.ForEach(c => c.IsSupported = (string.IsNullOrEmpty(Id) && c.Specificulture == Specificulture) || Repository.CheckIsExists(a => a.Id == Id && a.Specificulture == c.Specificulture, _context, _transaction) ); this.ActivedModules = new List <BEModuleViewModel>(); foreach (var module in this.ModuleNavs.Where(m => m.IsActived)) { var getModule = BEModuleViewModel.Repository.GetSingleModel(m => m.Id == module.ModuleId && m.Specificulture == module.Specificulture, _context, _transaction); if (getModule.IsSucceed) { this.ActivedModules.Add(getModule.Data); this.ActivedModules.ForEach(m => m.LoadData(Id)); } } }
public ViewToDoDialog(IConfiguration configuration) : base(nameof(ViewToDoDialog)) { string[] paths = { ".", "Dialogs", "ViewToDoDialog", "ViewToDoDialog.lg" }; string fullPath = Path.Combine(paths); // Create instance of adaptive dialog. this._viewToDoDialog = new AdaptiveDialog(nameof(ViewToDoDialog)) { Generator = new TemplateEngineLanguageGenerator(Templates.ParseFile(fullPath)), // Create and use a LUIS recognizer on the child // Each child adaptive dialog can have its own recognizer. Recognizer = CreateCrossTrainedRecognizer(configuration), Triggers = new List <OnCondition>() { new OnBeginDialog() { Actions = new List <Dialog>() { // See if any list has any items. new IfCondition() { Condition = "count(user.lists.todo) != 0 || count(user.lists.grocery) != 0 || count(user.lists.shopping) != 0", Actions = new List <Dialog>() { // Get list type new TextInput() { Property = "dialog.listType", Prompt = new ActivityTemplate("${GetListType()}"), Value = "=@listType", AllowInterruptions = "!@listType && turn.recognized.score >= 0.7", Validations = new List <BoolExpression>() { // Verify using expressions that the value is one of todo or shopping or grocery "contains(createArray('todo', 'shopping', 'grocery', 'all'), toLower(this.value))", }, OutputFormat = "=toLower(this.value)", InvalidPrompt = new ActivityTemplate("${GetListType.Invalid()}"), MaxTurnCount = 2, DefaultValue = "todo", DefaultValueResponse = new ActivityTemplate("${GetListType.DefaultValueResponse()}") }, new SendActivity("${ShowList()}") }, ElseActions = new List <Dialog>() { new SendActivity("${NoItemsInLists()}") } }, }, }, // Help and chitchat is handled by qna new OnQnAMatch { Actions = new List <Dialog>() { new SendActivity("${@Answer}") } } } }; // Add named dialogs to the DialogSet. These names are saved in the dialog state. AddDialog(this._viewToDoDialog); // The initial child Dialog to run. InitialDialogId = nameof(ViewToDoDialog); }