public bool ChangePassword(string strUID, string strNewPwd) { string strPwdHash = Gadget.SalGenerateSalt(10); string strPwdSalt = Gadget.SalGenerateHashCode(strNewPwd + strPwdHash); return(dal.ChangePassword(strUID, strPwdHash, strPwdSalt)); }
public Hitbox(int X, int Y, int W, int ID, string TEXT, GiraffeFont FONT, Gadget GADGET) { x0 = X; y0 = Y; h = 13; gadget = GADGET; font = FONT; id = ID; text = TEXT; quads = 0; if (gadget == Gadget.Button) { w = W; tx = x0 + (W / 2) - ((text.Length * 9) / 2); ty = y0 + 2; } else { w = 13; tx = x0 + 15; ty = y0 + 2; quads++; } x1 = X + W; y1 = Y + h; quads += 3 + FONT.Estimate(text); }
public string LogOn(string strEmail, string strPwd) { string strPwdHash = ""; string strPwdSalt = ""; IList <Model.User> listUser = dal.GetUser("", strEmail); if (listUser != null) { Model.User user = listUser[0]; strPwdSalt = user.MoyeBuyComPwdSalt; strPwdHash = user.MoyeBuyComPwdHash; string strNewPwdHash = Gadget.SalGenerateHashCode(strPwd + strPwdSalt); if (strNewPwdHash == strPwdHash) { return(WebConstant.LoginSuccess); } else { return(WebConstant.PwdIncorrect); } } else { return(WebConstant.UserNotExist); } }
public deleteWindow(Gadget gadget) { InitializeComponent(); gadgetDeleteViewModel = new GadgetDeleteViewModel(gadget); DataContext = gadgetDeleteViewModel; }
public void UpdateGadget(Gadget gadget) { // Copy gadget, otherwise binding would change displayed data Gadget copyGadget = new Gadget { InventoryNumber = gadget.InventoryNumber, Name = gadget.Name, Price = gadget.Price, Condition = gadget.Condition, Manufacturer = gadget.Manufacturer }; NewEditGadgetWindow singleGadgetWindow = new NewEditGadgetWindow(copyGadget); if (singleGadgetWindow.ShowDialog() == true) { // Copy back gadget.InventoryNumber = copyGadget.InventoryNumber; gadget.Name = copyGadget.Name; gadget.Price = copyGadget.Price; gadget.Condition = copyGadget.Condition; gadget.Manufacturer = copyGadget.Manufacturer; if (_service.UpdateGadget(gadget)) { LoadServerData(); } else { throw new Exception("Update Gadget Failed!"); } } copyGadget = null; }
private void RemoveGadget_Click(object sender, RoutedEventArgs e) { if (GadgetItems.SelectedIndex < 0) { MessageBox.Show("Please select one Gadget!"); return; } if (GadgetItems.SelectedValue.GetType() == typeof(Gadget)) { Gadget selectedGadget = (Gadget)GadgetItems.SelectedValue; Console.WriteLine("selected gadget: " + selectedGadget.ToString()); string deleteConfirmation = "Do you really want to delete " + selectedGadget.Name + " " + selectedGadget.Manufacturer + " ?"; if (MessageBox.Show(deleteConfirmation, "Confirmation", MessageBoxButton.YesNoCancel, MessageBoxImage.Warning) == MessageBoxResult.Yes) { if (!new LibraryAdminService(serverUrl).DeleteGadget(selectedGadget)) { MessageBox.Show("Could not delete gadget: " + selectedGadget.Name + " " + selectedGadget.Manufacturer); } else { MessageBox.Show("Gadget deleted: " + selectedGadget.Name + " " + selectedGadget.Manufacturer); } } } }
public AddGadget() { InitializeComponent(); EditedGadget = new Gadget("neues Gadget"); lib = new LibraryAdminService(serverUrl); //Inventorynumber erzeugen long highestValue = 0; List <Gadget> tabelle = lib.GetAllGadgets(); foreach (Gadget i in tabelle) { if (i.InventoryNumber != null) { long newNumber = long.Parse(i.InventoryNumber); if (highestValue < newNumber) { highestValue = newNumber; } } } EditedGadget.InventoryNumber = "" + ++highestValue; DataContext = this; }
public static void AutoRequestTroops(Gadget gg) { DebuggingAndTracking.Debug.Logging("AutoRequestTroops - Units start"); //force unit int nCities = Gloval.Database.Account.Cities.Count(); //giảm dc 1 request if (Gloval.Database.CurrentCity == 0) { for (int i = 0; i < nCities; i++) { if (gg.bStopAutoRequest) { return; } BUSTroops.requestUnits(i); } } else { for (int i = nCities - 1; i >= 0; i--) { if (gg.bStopAutoRequest) { return; } BUSTroops.requestUnits(i); } } DebuggingAndTracking.Debug.Logging("AutoRequestTroops - Units done"); DebuggingAndTracking.Debug.Logging("AutoRequestTroops - Ships start"); //giảm dc 1 request if (Gloval.Database.CurrentCity == 0) { for (int i = 0; i < nCities; i++) { if (gg.bStopAutoRequest) { return; } BUSTroops.requestShips(i); } } else { for (int i = nCities - 1; i >= 0; i--) { if (gg.bStopAutoRequest) { return; } BUSTroops.requestShips(i); } } Gloval.bTroopsOverviewIsNewData = true; DebuggingAndTracking.Debug.Logging("AutoRequestTroops - Ships done"); }
public static void AutoRequestBuildings(Gadget gg) { DebuggingAndTracking.Debug.Logging("AutoRequestBuildings start"); //force update building int nCities = Gloval.Database.Account.Cities.Count(); //giảm dc 1 request if (Gloval.Database.CurrentCity == 0) { for (int i = 0; i < nCities; i++) { if (gg.bStopAutoRequest) { return; } BUSBuilding.requestBuilding(i); } } else { for (int i = nCities - 1; i >= 0; i--) { if (gg.bStopAutoRequest) { return; } BUSBuilding.requestBuilding(i); } } Gloval.bBuildingsOverviewIsNewData = true; DebuggingAndTracking.Debug.Logging("AutoRequestBuildings start"); }
public Expose178.Com.Model.ArticleAddtional GetArticleAddtional(string strArticleID) { Expose178.Com.Model.ArticleAddtional addtion = new Model.ArticleAddtional(); try { DataSet dsArticleAdd = GetArticleAddtionalByArticleID(strArticleID); if (Gadget.DatatSetIsNotNullOrEmpty(dsArticleAdd)) { addtion.AdditionalID = Gadget.GetDataRowStringValue(dsArticleAdd.Tables[0].Rows[0], "AdditionalID"); addtion.ArticleID = strArticleID; addtion.LastUpdatedDate = Gadget.GetDataRowDateTimeValue(dsArticleAdd.Tables[0].Rows[0], "LastUpdatedDate"); addtion.ReadNum = Gadget.GetDataRowIntValue(dsArticleAdd.Tables[0].Rows[0], "ReadNum"); addtion.ReplyNum = Gadget.GetDataRowIntValue(dsArticleAdd.Tables[0].Rows[0], "ReplyNum"); addtion.UpdatedByUserID = Gadget.GetDataRowStringValue(dsArticleAdd.Tables[0].Rows[0], "UpdatedByUserID"); } } catch (Exception ex) { Hashtable hshParam = new Hashtable(); hshParam.Add("Error", ex.Message); hshParam.Add("UID", Expose178.Com.GadgetScripts.Gadget.GetUserID()); Expose178.Com.UtilityFactory.Log.WriteLog(hshParam, "ProxyArticle.GetArticleAddtional", UtilityFactory.LogType.LogToDB); } return(addtion); }
void OnTriggerEnter(Collider other) { Gadget otherGadget = other.gameObject.GetComponentInParent <Gadget>(); if (ShouldIgnoreCollision(otherGadget)) { return; } if (!GameManager.Instance.IsGameOver) { this.IsGoalComplete = true; World.Instance.NotifyGoalComplete(); LineRenderer[] lasers = this.GetComponentsInChildren <LineRenderer>(); foreach (LineRenderer laser in lasers) { laser.material.color = Color.green; laser.material.SetColor("_TintColor", Color.green); laser.startColor = Color.green; laser.endColor = Color.green; } } }
void Awake() { if (instance == null) { instance = this; } }
public void InitLoadout(LoadoutData loadoutRef) { Loadout newLoadout = new Loadout(); if (loadoutRef.gun) { Gun gun = Instantiate(loadoutRef.gun); Equip(gun, Anim.GetBoneTransform(HumanBodyBones.RightHand)); newLoadout.gun = gun; } if (loadoutRef.grenade) { Grenade grenade = Instantiate(loadoutRef.grenade); Equip(grenade, Vector3.zero, Quaternion.identity); newLoadout.grenade = grenade; } if (loadoutRef.gadget) { Gadget gadget = Instantiate(loadoutRef.gadget); Equip(gadget, Vector3.zero, Quaternion.identity); newLoadout.gadget = gadget; } loadout = newLoadout; }
/// <summary> /// Invoked when an unhandled Keyboard.PreviewKeyDown attached event reaches an element in its route that is derived from this class. /// </summary> /// <param name="e">The KeyboardFocusChangedEventArgs that contains the event data.</param> protected override void OnPreviewLostKeyboardFocus(KeyboardFocusChangedEventArgs e) { // Validate the parameters. if (e == null) { throw new ArgumentNullException("e"); } // This will attempt to fix a bug with the Menu class. When an item is selected from the submenu of a top-level MenuItem, or when the user hits Escape // in a Menu, the base class attempts to clear the "MenuMode" and "Restore the Previous Focus". This creates serious problems when the current // MenuItem is also the current focus element of the main window because WPF attempts to restore to focus to the element that already has the focus and // gets confused. The end effect is that the current item is de-selected even though it still has the focus. This logic attempts to intercept the // "Restore Previous Focus" logic and make it work intuitively by keeping allowing the item with the keyboard focus to stay 'selected' in the menu. UIElement oldFocusElement = e.OldFocus as UIElement; UIElement newFocusElement = e.NewFocus as UIElement; if (newFocusElement != null && this.IsDescendantOf(newFocusElement) && oldFocusElement != null && this.IsAncestorOf(oldFocusElement)) { Gadget gadget = oldFocusElement as Gadget; if (gadget != null) { gadget.SimulateIsKeyboardFocusWithinChanged(); } } // Though there is no default implementation, it is recommend that the base class should be called. base.OnPreviewLostKeyboardFocus(e); }
public Gadget AddGadget(Gadget newGadget) { //Gadget existingObj = GetGadget(newGadget); //if (existingObj == null) //{ //Vendor, Author, Metadata to DB - if they exist their ID is returned, otherwise they are added and the new ID is returned Gadget gadgetToAdd = new Gadget(); gadgetToAdd.VendorId = DAVendor.Instance.AddVendor(newGadget.Vendor); gadgetToAdd.AuthorId = DAAuthor.Instance.AddAuthor(newGadget.Author); gadgetToAdd.GadgetMetadataId = DAGadgetMetadata.Instance.AddGadgetMetadata(newGadget.GadgetMetadata); //build URI and ULR gadgetToAdd.GadgetUri = string.Format(uriForamt, newGadget.Owner, newGadget.GadgetMetadata.GadgetName, newGadget.Version); gadgetToAdd.AbsoluteURL = "baseURL" + gadgetToAdd.GadgetUri; //copy rest of data gadgetToAdd.Owner = newGadget.Owner; gadgetToAdd.Version = newGadget.Version; gadgetToAdd.NoContent = true; base.DataContext.Gadgets.InsertOnSubmit(gadgetToAdd); base.DataContext.SubmitChanges(); return gadgetToAdd; //} //else //{ // return existingObj; //} }
/// <summary> /// Removes a gadget from database. /// </summary> /// <param name="g"></param> public static void RemoveGadget(Gadget g) { AppDataModelContainer context = new AppDataModelContainer(); context.Gadgets.Remove(g); context.SaveChanges(); }
public Expose178.Com.Model.Article GetArticle(string strArticleID) { Expose178.Com.Model.Article art = new Model.Article(); DataSet dsArticle = GetArticleByID(strArticleID); if (Gadget.DatatSetIsNotNullOrEmpty(dsArticle)) { art.ArticleID = strArticleID; art.ArticleTile = Gadget.GetDataRowStringValue(dsArticle.Tables[0].Rows[0], "ArticleTile"); art.ArticleDate = Gadget.GetDataRowDateTimeValue(dsArticle.Tables[0].Rows[0], "ArticleDate"); art.ArticleBody = Gadget.GetDataRowStringValue(dsArticle.Tables[0].Rows[0], "ArticleBody"); art.BackgroundImgUrl = Gadget.GetDataRowStringValue(dsArticle.Tables[0].Rows[0], "BackgroundImgUrl"); art.IsDraft = Gadget.GetDataRowBoolValue(dsArticle.Tables[0].Rows[0], "IsDraft"); art.IsValidated = Gadget.GetDataRowBoolValue(dsArticle.Tables[0].Rows[0], "IsValidated"); art.LastUpdatedDate = Gadget.GetDataRowDateTimeValue(dsArticle.Tables[0].Rows[0], "LastUpdatedDate"); string strUID = Gadget.GetDataRowStringValue(dsArticle.Tables[0].Rows[0], "UpdatedByUserID"); string strstrAritcleTypeCode = Gadget.GetDataRowStringValue(dsArticle.Tables[0].Rows[0], "AritcleTypeCode"); string strReadRoleTypeCode = Gadget.GetDataRowStringValue(dsArticle.Tables[0].Rows[0], "ReadRoleTypeCode"); ArticleReply reply = new ArticleReply(); User user = new User(); art.ListReply = reply.GetListReplyToArticle(strArticleID); art.ReadRoleType = GetReadRoleType(strReadRoleTypeCode); art.User = user.GetUserByUID(strUID); art.AritcleType = GetAritcleType(strstrAritcleTypeCode); } return(art); }
// Start is called before the first frame update void Start() { CommunicationEvents.ToolModeChangedEvent.AddListener(OnToolModeChanged); gadgets = GetComponentsInChildren <Gadget>(); for (int i = 0; i < gadgets.Length; i++) { gadgets[i].id = i; //Create Buttons and add them to UI CreateButton(gadgets[i]); if (i == 0) { gadgets[i].gameObject.SetActive(true); activeGadget = gadgets[i]; } else { gadgets[i].gameObject.SetActive(false); } } //Activate UI (using buttons) GadgetUI.GetComponent <ToolModeSelector>().enabled = true; }
private void DeleteGadget_Click(object sender, RoutedEventArgs e) { if (gadgetGrid.SelectedItem == null) { MessageBox.Show("No Item selected!"); } else { Gadget selectedGadget = (Gadget)gadgetGrid.SelectedItem; deleteGadget deleteWindow = new deleteGadget(selectedGadget); deleteWindow.Show(); deleteWindow.Yes_Button.Click += delegate { if (service.DeleteGadget(selectedGadget)) { //MessageBox.Show("Gadget successfully deleted!"); deleteWindow.Close(); } else { MessageBox.Show("Operation failed!"); } }; deleteWindow.Closed += delegate(object s, EventArgs a) { RefreshGadgets(); }; } }
public int ReplyTo(string email) { int cnt = 0; string s = email; s = s.Replace(" ", ""); s = s.Replace(",", " "); s = s.Replace(";", " "); string[] words = s.Split(' '); Gadget g = new Gadget(); foreach (string word in words) { if (g.checkEmail(word)) { try { message.ReplyToList.Add(word); cnt++; } catch { } } } return(cnt); }
public void DeleteGadget(Gadget gadget) { Gadget dbEntry = context.Gadgets.Find(gadget.GadgetId); context.Gadgets.Remove(dbEntry); context.SaveChanges(); }
public int addTo(string email) { //test if only one email int cnt = 0; string s = email; s = s.Replace(" ", ""); s = s.Replace(",", " "); s = s.Replace(";", " "); string[] words = s.Split(' '); Gadget g = new Gadget(); foreach (string word in words) { if (g.checkEmail(word)) { try { MailAddress address = new MailAddress(word); message.To.Add(address); cnt++; } catch { } } } return(cnt); }
/// <summary> /// Inserts a new gadget into the database /// </summary> /// <param name="data"></param> /// <returns></returns> public ObjectReturnData <Gadget2> InsertGadget(GadgetInsertData data) { try { //Insert row into database and read back object int id = _dataAccess.Insert <int, GadgetInsertData>(data, StoredProcedureTypes.Insert); Gadget gadget = _dataAccess.GetObjectById <int, Gadget>(id, StoredProcedureTypes.ById); Gadget2 g2 = new Gadget2(); g2.Populate(gadget); ObjectReturnData <Gadget2> returnObject = new ObjectReturnData <Gadget2> { Id = id.ToString(), //Easier to deal with Id as a string in javascript Value = g2, // Adds UpdateDateTimeString so javascript doesn't have to convert the time to a string IsSuccessful = true }; return(returnObject); } catch (Exception ex) { ObjectReturnData <Gadget2> returnObject = new ObjectReturnData <Gadget2>() { //In produciton code ex.ToString() should be logged and a more user friend error message should be returned ErrorMessage = ex.ToString(), CallingMethod = (new System.Diagnostics.StackTrace()).GetFrame(1).GetMethod().Name, //method that called this method IsSuccessful = false }; return(returnObject); } }
public RewriterResults rewrite(Gadget gadget, MutableContent content) { if (gadget.getSpec().getModulePrefs().getFeatures().ContainsKey("caja") || "1".Equals(gadget.getContext().getParameter("caja"))) { URI retrievedUri = gadget.getContext().getUrl(); UriCallback2 cb = new UriCallback2(retrievedUri); MessageQueue mq = new SimpleMessageQueue(); DefaultGadgetRewriter rw = new DefaultGadgetRewriter(mq); CharProducer input = CharProducer.Factory.create( new java.io.StringReader(content.getContent()), FilePosition.instance(new InputSource(new java.net.URI(retrievedUri.ToString())), 2, 1, 1)); java.lang.StringBuilder output = new java.lang.StringBuilder(); try { rw.rewriteContent(new java.net.URI(retrievedUri.ToString()), input, cb, output); } catch (GadgetRewriteException e) { throwCajolingException(e, mq); return RewriterResults.notCacheable(); } catch (IOException e) { throwCajolingException(e, mq); return RewriterResults.notCacheable(); } content.setContent(tameCajaClientApi() + output.ToString()); } return null; }
public async Task <IHttpActionResult> PutGadget(int id, Gadget gadget) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != gadget.GadgetID) { return(BadRequest()); } db.Entry(gadget).State = EntityState.Modified; try { await db.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!GadgetExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }
/// <summary> /// Responds to the KeyDown event. /// </summary> /// <param name="e">A KeyEventArgs that contains the event data.</param> protected override void OnKeyDown(KeyEventArgs e) { // Validate the parameters. if (e == null) { throw new ArgumentNullException("e"); } // There is an inconsistency if not an outright bug with WPF's handling of the menus. When you open up a submenu, the mouse is captured by the MenuBase // class. When you click on the menu item again, the submenu disappears and the mouse capture is released. However, when you hit the escape key, the // submenu disappears but the mouse capture is retained until you hit the Escape key again. To fix this bug (there is no reason for the MenuBase to // retain the mouse capture when non of the submenus are open), the submenu is closed here before the key is processed. While this doesn't appear to have // any reasonable side-effect, it kicks logic into place deep in the MenuBase class that will close out the menu mode properly. if (e.Key == Key.Escape) { Gadget gadget = this.CurrentSelection; if (gadget != null && gadget.IsSubmenuOpen) { gadget.IsSubmenuOpen = false; } } // The base class has considerable processing on this message that needs to be completed. base.OnKeyDown(e); }
private void CreateNewGadget() { GadgetNotSaved = true; NewGadget = new Gadget(""); Gadgets.Add(NewGadget); SelectedGadget = NewGadget; }
public void CreateGadget() { var domObj = new Gadget() { Name = "Valid Name", Description = "Valid description", Price = 1, Image = "Valid Image", CategoryID = 1 }; var response = MyWebApi .Server() .Working() .WithHttpRequestMessage( request => request .WithMethod(HttpMethod.Post) .WithRequestUri("/api/Gadgets") .WithJsonContent(JsonConvert.SerializeObject(domObj))) .ShouldReturnHttpResponseMessage() .WithStatusCode(HttpStatusCode.OK) .WithResponseModelOfType <GadgetViewModel>() .AndProvideTheModel(); Assert.That(response.GadgetID, Is.GreaterThan(0)); createdId = response.GadgetID; }
private void funcAddGadget(Window window) { if (!string.IsNullOrWhiteSpace(newGadget.Name) && !string.IsNullOrWhiteSpace(newGadget.Manufacturer) && newGadget.Price > 0) { var gadget = new Gadget(newGadget.Name) { Manufacturer = newGadget.Manufacturer, Price = newGadget.Price, Condition = newGadget.Condition }; if (!service.AddGadget(gadget)) { // Error Output MessageBox.Show($"{gadget} konnte nicht hinzugefügt werden..."); Console.WriteLine($"{gadget} konnte nicht hinzugefügt werden..."); } else { window.Close(); } } else { // Do nothing MessageBox.Show("Bitte alle Felder ausfüllen."); Console.WriteLine("Bitte alle Felder ausfüllen."); } }
public String sendTheEmail(string destinationemail, string sourceemail, string messagebody, string mailsubject) { String response = ""; Gadget g = new Gadget(); if (g.checkEmail(destinationemail)) { try { string body = messagebody; // ISMJob.ServiceReference1.ServiceSoapClient ws = new ISMJob.ServiceReference1.ServiceSoapClient(); response = "";// ws.SendMail("*****@*****.**", "*****@*****.**", body, "Test Email Subject"); } catch (Exception ex) { errmsg = "ERR: " + ex.Message; return("false"); } return(response); } else { return(response = "-1"); } }
public RewriterResults rewrite(Gadget gadget, MutableContent content) { if (gadget.getSpec().getModulePrefs().getFeatures().ContainsKey("caja") || "1".Equals(gadget.getContext().getParameter("caja"))) { URI retrievedUri = gadget.getContext().getUrl(); UriCallback2 cb = new UriCallback2(retrievedUri); MessageQueue mq = new SimpleMessageQueue(); DefaultGadgetRewriter rw = new DefaultGadgetRewriter(mq); CharProducer input = CharProducer.Factory.create( new java.io.StringReader(content.getContent()), FilePosition.instance(new InputSource(new java.net.URI(retrievedUri.ToString())), 2, 1, 1)); java.lang.StringBuilder output = new java.lang.StringBuilder(); try { rw.rewriteContent(new java.net.URI(retrievedUri.ToString()), input, cb, output); } catch (GadgetRewriteException e) { throwCajolingException(e, mq); return(RewriterResults.notCacheable()); } catch (IOException e) { throwCajolingException(e, mq); return(RewriterResults.notCacheable()); } content.setContent(tameCajaClientApi() + output.ToString()); } return(null); }
public void AddGadget(Gadget gadget) { context.Gadgets.Add(gadget); context.SaveChanges(); int id = gadget.GadgetId; }
public RewriterResults rewrite(Gadget gadget, MutableContent mutableContent) { Document document = mutableContent.getDocument(); Element head = (Element)DomUtil.getFirstNamedChildNode(document.getDocumentElement(), "head"); // Remove all the elements currently in head and add them back after we inject content NodeList children = head.getChildNodes(); List<Node> existingHeadContent = new List<Node>(children.getLength()); for (int i = 0; i < children.getLength(); i++) { existingHeadContent.Add(children.item(i)); } foreach(Node n in existingHeadContent) { head.removeChild(n); } // Only inject default styles if no doctype was specified. if (document.getDoctype() == null) { Element defaultStyle = document.createElement("style"); defaultStyle.setAttribute("type", "text/css"); head.appendChild(defaultStyle); defaultStyle.appendChild(defaultStyle.getOwnerDocument(). createTextNode(DEFAULT_CSS)); } InjectBaseTag(gadget, head); InjectFeatureLibraries(gadget, head); // This can be one script block. Element mainScriptTag = document.createElement("script"); InjectMessageBundles(gadget, mainScriptTag); InjectDefaultPrefs(gadget, mainScriptTag); InjectPreloads(gadget, mainScriptTag); // We need to inject our script before any developer scripts. head.appendChild(mainScriptTag); Element body = (Element)DomUtil.getFirstNamedChildNode(document.getDocumentElement(), "body"); LocaleSpec localeSpec = gadget.getLocale(); if (localeSpec != null) { body.setAttribute("dir", localeSpec.getLanguageDirection()); } // re append head content foreach(Node node in existingHeadContent) { head.appendChild(node); } InjectOnLoadHandlers(body); mutableContent.documentChanged(); return RewriterResults.notCacheable(); }
/** * Render the gadget into a string by performing the following steps: * * - Retrieve gadget specification information (GadgetSpec, MessageBundle, etc.) * * - Fetch any preloaded data needed to handle the request, as handled by Preloader. * * - Perform rewriting operations on the output content, handled by Rewriter. * * @param gadget The gadget for the rendering operation. * @return The rendered gadget content * @throws RenderingException if any issues arise that prevent rendering. */ public String render(Gadget gadget) { try { View view = gadget.getCurrentView(); GadgetContext context = gadget.getContext(); GadgetSpec spec = gadget.getSpec(); IPreloads preloads = preloader.preload(context, spec, PreloaderService.PreloadPhase.HTML_RENDER); gadget.setPreloads(preloads); String content; if (view.getHref() == null) { content = view.getContent(); } else { // TODO: Add current url to GadgetContext to support transitive proxying. UriBuilder uri = new UriBuilder(view.getHref()); uri.addQueryParameter("lang", context.getLocale().getLanguage()); uri.addQueryParameter("country", context.getLocale().getCountry()); sRequest request = new sRequest(uri.toUri()) .setIgnoreCache(context.getIgnoreCache()) .setOAuthArguments(new OAuthArguments(view)) .setAuthType(view.getAuthType()) .setSecurityToken(context.getToken()) .setContainer(context.getContainer()) .setGadget(spec.getUrl()); sResponse response = DefaultHttpCache.Instance.getResponse(request); if (response == null || response.isStale()) { sRequest proxyRequest = createPipelinedProxyRequest(gadget, request); response = requestPipeline.execute(proxyRequest); DefaultHttpCache.Instance.addResponse(request, response); } if (response.isError()) { throw new RenderingException("Unable to reach remote host. HTTP status " + response.getHttpStatusCode()); } content = response.responseString; } return rewriter.rewriteGadget(gadget, content); } catch (GadgetException e) { throw new RenderingException(e.Message, e); } }
/** * izveido buuvdarbu (sho netaisa prefabam caur Unity inspektoru, jo shis ir iislaiciigi pieejams darbs) */ public void CreateAndAddConstructionJob(Room block, Gadget gadget, WorkUnit.WorkUnitTypes workType) { WorkUnit constructionJob = new WorkUnit(); constructionJob.parentGameobject = block.gameObject; constructionJob.parentGadget = gadget;//null, ja shis nav gadzheta darbs constructionJob.WorkUnitTypeNumber = workType; constructionJob.setOn(true); AddWork(constructionJob); }
public String rewriteGadget(Gadget gadget, View currentView) { if (currentView == null) { // Nothing to rewrite. return null; } MutableContent mc = GetMutableContent(gadget.getSpec(), currentView); foreach(IContentRewriter rewriter in rewriters) { rewriter.rewrite(gadget, mc); } return mc.getContent(); }
public String rewriteGadget(Gadget gadget, String content) { if (content == null) { // Nothing to rewrite. return null; } MutableContent mc = GetMutableContent(content); foreach(IContentRewriter rewriter in rewriters) { rewriter.rewrite(gadget, mc); } return mc.getContent(); }
public void UpdateGadgetContent(Gadget objGadget, bool noContent) { objGadget.NoContent = noContent; base.DataContext.SubmitChanges(); }
/// <summary> /// Injects javascript libraries needed to satisfy feature dependencies. /// </summary> /// <param name="gadget"></param> /// <param name="headTag"></param> private void InjectFeatureLibraries(Gadget gadget, Node headTag) { // TODO: If there isn't any js in the document, we can skip this. Unfortunately, that means // both script tags (easy to detect) and event handlers (much more complex). GadgetContext context = gadget.getContext(); GadgetSpec spec = gadget.getSpec(); String forcedLibs = context.getParameter("libs"); HashKey<String> forced; if (string.IsNullOrEmpty(forcedLibs)) { forced = new HashKey<string>(); } else { forced = new HashKey<string>(); foreach (var item in forcedLibs.Split(':')) { forced.Add(item); } } // Forced libs are always done first. if (forced.Count != 0) { String jsUrl = urlGenerator.getBundledJsUrl(forced, context); Element libsTag = headTag.getOwnerDocument().createElement("script"); libsTag.setAttribute("src", jsUrl); headTag.appendChild(libsTag); // Forced transitive deps need to be added as well so that they don't get pulled in twice. // TODO: Figure out a clean way to avoid having to call getFeatures twice. foreach(GadgetFeature dep in featureRegistry.GetFeatures(forced)) { forced.Add(dep.getName()); } } // Inline any libs that weren't forced. The ugly context switch between inline and external // Js is needed to allow both inline and external scripts declared in feature.xml. String container = context.getContainer(); ICollection<GadgetFeature> features = GetFeatures(spec, forced); // Precalculate the maximum length in order to avoid excessive garbage generation. int size = 0; foreach(GadgetFeature feature in features) { foreach(JsLibrary library in feature.getJsLibraries(RenderingContext.GADGET, container)) { if (library._Type == JsLibrary.Type.URL) { size += library.Content.Length; } } } // Really inexact. StringBuilder inlineJs = new StringBuilder(size); foreach (GadgetFeature feature in features) { foreach (JsLibrary library in feature.getJsLibraries(RenderingContext.GADGET, container)) { if (library._Type == JsLibrary.Type.URL) { if (inlineJs.Length > 0) { Element inlineTag = headTag.getOwnerDocument().createElement("script"); headTag.appendChild(inlineTag); inlineTag.appendChild(headTag.getOwnerDocument().createTextNode(inlineJs.ToString())); inlineJs.Length = 0; } Element referenceTag = headTag.getOwnerDocument().createElement("script"); referenceTag.setAttribute("src", library.Content); headTag.appendChild(referenceTag); } else { if (!forced.Contains(feature.getName())) { // already pulled this file in from the shared contents. if (context.getDebug()) { inlineJs.Append(library.DebugContent); } else { inlineJs.Append(library.Content); } inlineJs.Append(";\n"); } } } } inlineJs.Append(GetLibraryConfig(gadget, features)); if (inlineJs.Length > 0) { Element inlineTag = headTag.getOwnerDocument().createElement("script"); headTag.appendChild(inlineTag); inlineTag.appendChild(headTag.getOwnerDocument().createTextNode(inlineJs.ToString())); } }
private void InjectBaseTag(Gadget gadget, Node headTag) { GadgetContext context = gadget.getContext(); if ("true".Equals(containerConfig.Get(context.getContainer(), INSERT_BASE_ELEMENT_KEY))) { Uri baseUrl = gadget.getSpec().getUrl(); View view = gadget.getCurrentView(); if (view != null && view.getHref() != null) { baseUrl = view.getHref(); } Element baseTag = headTag.getOwnerDocument().createElement("base"); baseTag.setAttribute("href", baseUrl.ToString()); headTag.insertBefore(baseTag, headTag.getFirstChild()); } }
/** * Injects message bundles into the gadget output. * @throws GadgetException If we are unable to retrieve the message bundle. */ private void InjectMessageBundles(Gadget gadget, Node scriptTag) { GadgetContext context = gadget.getContext(); MessageBundle bundle = messageBundleFactory.getBundle( gadget.getSpec(), context.getLocale(), context.getIgnoreCache()); String msgs = bundle.ToJSONString(); Text text = scriptTag.getOwnerDocument().createTextNode("gadgets.Prefs.setMessages_("); text.appendData(msgs); text.appendData(");"); scriptTag.appendChild(text); }
/** * Creates a set of all configuration needed to satisfy the requested feature set. * * Appends special configuration for gadgets.util.hasFeature and gadgets.util.getFeatureParams to * the output js. * * This can't be handled via the normal configuration mechanism because it is something that * varies per request. * * @param reqs The features needed to satisfy the request. * @throws GadgetException If there is a problem with the gadget auth token */ private String GetLibraryConfig(Gadget gadget, ICollection<GadgetFeature> reqs) { GadgetContext context = gadget.getContext(); JsonObject features = containerConfig.GetJsonObject(context.getContainer(), FEATURES_KEY); Dictionary<String, Object> config = new Dictionary<string, object>(features == null ? 2 : features.Names.Count + 2); if (features != null) { // Discard what we don't care about. foreach (GadgetFeature feature in reqs) { String name = feature.getName(); Object conf = features.Opt(name); if (conf != null) { config.Add(name, conf); } } } // Add gadgets.util support. This is calculated dynamically based on request inputs. ModulePrefs prefs = gadget.getSpec().getModulePrefs(); var values = prefs.getFeatures().Values; Dictionary<String, Dictionary<String, String>> featureMap = new Dictionary<string, Dictionary<string, string>>(values.Count); foreach(Feature feature in values) { featureMap.Add(feature.getName(), feature.getParams()); } config.Add("core.util", featureMap); // Add authentication token config ISecurityToken authToken = context.getToken(); if (authToken != null) { Dictionary<String,String> authConfig = new Dictionary<String,String>(2); String updatedToken = authToken.getUpdatedToken(); if (updatedToken != null) { authConfig.Add("authToken", updatedToken); } String trustedJson = authToken.getTrustedJson(); if (trustedJson != null) { authConfig.Add("trustedJson", trustedJson); } config.Add("shindig.auth", authConfig); } return "gadgets.config.init(" + JsonConvert.ExportToString(config) + ");\n"; }
/** * Injects preloads into the gadget output. * * If preloading fails for any reason, we just output an empty object. */ private static void InjectPreloads(Gadget gadget, Node scriptTag) { IPreloads preloads = gadget.getPreloads(); Dictionary<String, Object> preload = new Dictionary<string, object>(); foreach(PreloadedData preloaded in preloads.getData()) { foreach(var entry in preloaded.toJson()) { preload.Add(entry.Key, entry.Value); } } Text text = scriptTag.getOwnerDocument().createTextNode("gadgets.io.preloaded_="); text.appendData(JsonConvert.ExportToString(preload)); text.appendData(";"); scriptTag.appendChild(text); }
/** * Injects default values for user prefs into the gadget output. */ private static void InjectDefaultPrefs(Gadget gadget, Node scriptTag) { List<UserPref> prefs = gadget.getSpec().getUserPrefs(); Dictionary<String, String> defaultPrefs = new Dictionary<string, string>(prefs.Count); foreach(UserPref up in gadget.getSpec().getUserPrefs()) { defaultPrefs.Add(up.getName(), up.getDefaultValue()); } Text text = scriptTag.getOwnerDocument().createTextNode("gadgets.Prefs.setDefaultPrefs_("); text.appendData(JsonConvert.ExportToString(defaultPrefs)); text.appendData(");"); scriptTag.appendChild(text); }
/** * Creates a proxy request by fetching pipelined data and adding it to an existing request. * */ private sRequest createPipelinedProxyRequest(Gadget gadget, sRequest original) { sRequest request = new sRequest(original); request.setIgnoreCache(true); GadgetSpec spec = gadget.getSpec(); GadgetContext context = gadget.getContext(); IPreloads proxyPreloads = preloader.preload(context, spec, PreloaderService.PreloadPhase.PROXY_FETCH); // TODO: Add current url to GadgetContext to support transitive proxying. // POST any preloaded content if ((proxyPreloads != null) && proxyPreloads.getData().Count != 0) { JsonArray array = new JsonArray(); foreach(PreloadedData preload in proxyPreloads.getData()) { Dictionary<String, Object> dataMap = preload.toJson(); foreach(var entry in dataMap) { // TODO: the existing, supported content is JSONObjects that contain the // key already. Discarding the key is odd. array.Put(entry.Value); } } String postContent = array.ToString(); // POST the preloaded content, with a method override of GET // to enable caching request.setMethod("POST") .setPostBody(Encoding.UTF8.GetBytes(postContent)) .setHeader("Content-Type", "text/json;charset=utf-8"); } return request; }
public Gadget GetGadget(Gadget newGadget) { //return base.DataContext.Gadgets.Single<Gadget>(g => (g.Owner == newGadget.Owner && ); foreach (Gadget g in base.DataContext.Gadgets) { if (g.IsDeleted == false) { if (g.Equals(newGadget)) return g; } } return null; }
public Gadget UpdateGadget(Gadget newGadget) { Gadget oldGadget = GetGadgetById(newGadget.GadgetUri); oldGadget = newGadget; base.DataContext.SubmitChanges(); return oldGadget; }
public virtual RewriterResults rewrite(Gadget gadget, MutableContent content) { java.io.StringWriter sw = new java.io.StringWriter(); GadgetSpec spec = gadget.getSpec(); Uri _base = spec.getUrl(); View view = gadget.getCurrentView(); if (view != null && view.getHref() != null) { _base = view.getHref(); } if (rewrite(spec, _base, content, "text/html", sw)) { content.setContent(sw.toString()); } return null; }
private Uri getRedirect(Gadget gadget) { // TODO: This should probably just call UrlGenerator.getIframeUrl(), but really it should // never happen. View view = gadget.getCurrentView(); if (view.getType() == View.ContentType.URL) { return gadget.getCurrentView().getHref(); } // TODO return null; }
public bool DeleteGadget(Gadget deleteGadget, bool physicalDeleteSuccesfull) { deleteGadget.NoContent = physicalDeleteSuccesfull; deleteGadget.IsDeleted = true; base.DataContext.SubmitChanges(); return true; }
public void RemoveAllConstructionJobsForThisGadget(Gadget gadget) { int i = 0; foreach(WorkUnit w in worklist) { if(w.parentGadget == gadget && (int)w.WorkUnitTypeNumber > 2 &&(int)w.WorkUnitTypeNumber <= 4) { //shim gadzhetam piederoshs buuvdarbs w.setOn(false,true); //svariigi izsleegt, citaadi nabaga agjents straadaas liidz darbalaika beigaam worklist.RemoveAt(i); RemoveAllConstructionJobsForThisGadget(gadget); //izmainiiju listi, taapeec nevaru turpinaat ciklu, atlikushos jaaskata jaunaa ciklaa return; } i++; } }
public virtual GadgetApplyError CanApplyGadget(Gadget gadget) { return GadgetApplyError.Success; }
/** * vai padotais gadzhets nepaarklaajas ar kaadu citu gadzhetu * Lietos vienkaarshotu, manuaalu AABB koliiziju noteikshanu */ public bool IsThisSpotFree(Gadget newGadget) { if(gadgetAtThisPosition(newGadget.transform.position.x,newGadget.transform.position.y,newGadget.SizeX,newGadget.SizeY) != null){ //shajaa poziicijaa ir atrasts kaads gadzhets return false; } return true; }