Inheritance: MonoBehaviour
Example #1
0
	///<summary>
	/// Creates a DLT.
	/// <param name="message">The Message to which this Type belongs</param>
	/// <param name="description">The description of this type</param>
	///</summary>
	public DLT(IMessage message, string description) : base(message, description){
		data = new IType[4];
		data[0] = new NR(message,"Normal Range");
		data[1] = new NM(message,"Numeric Threshold");
		data[2] = new ID(message, 523,"Change Computation");
		data[3] = new NM(message,"Days Retained");
	}
    public void GetEnumerator_Call_ReturnScoresWithKeyName(Db db, ID keyId1, ID keyId2, DbItem profileItem, IBehaviorProfileContext behaviorProfile)
    {
      //Arrange
      using (new SecurityDisabler())
      {
        profileItem.Add(new DbItem("Key1", keyId1, ProfileKeyItem.TemplateID)
        {
          {ProfileKeyItem.FieldIDs.NameField,"key1name" }
        });
        profileItem.Add(new DbItem("Key2", keyId2, ProfileKeyItem.TemplateID)
        {
          {ProfileKeyItem.FieldIDs.NameField,"key2name" }
        });

        db.Add(profileItem);

        var item = db.GetItem(profileItem.FullPath);
        var profile = new ProfileItem(item);

        var behaviorScores = new List<KeyValuePair<ID, float>>() { new KeyValuePair<ID, float>(keyId1, 10), new KeyValuePair<ID, float>(keyId2, 20) };
        behaviorProfile.Scores.Returns(behaviorScores);
        var behaviorProfileDecorator = new BehaviorProfileDecorator(profile, behaviorProfile);

        //Act
        var result = behaviorProfileDecorator.ToList();

        //Assert      
        result.Should().BeEquivalentTo(new[] { new KeyValuePair<string, float>("key1name", 10), new KeyValuePair<string, float>("key2name", 20) });
      }
    }
        public virtual void Execute(ID formId, AdaptedResultList fields, object[] data)
        {
            Assert.ArgumentNotNull(formId, "formid");
            Assert.ArgumentNotNull(data, "data");
            try
            {
                ID sessionId = ID.Null;
                if ((data != null) && (data.Length > 0))
                {
                    ID.TryParse(data[0], out sessionId);
                }

                _formReposiotry.Insert(formId, fields, sessionId,
                  ((data != null) && (data.Length > 1)) ? data[0].ToString() : null);
            }
            catch (EntityCommandExecutionException entityCommandExecutionException)
            {
                Exception innerException = entityCommandExecutionException;
                if (entityCommandExecutionException.InnerException != null)
                {
                    innerException = entityCommandExecutionException.InnerException;
                }
                Log.Error("Save To Database failed.", innerException, innerException);
                throw innerException;
            }
            catch (Exception exception)
            {
                Log.Error("Save To Database failed.", exception, exception);
                throw;
            }
        }
Example #4
0
File: MO.cs Project: snosrap/nhapi
 ///<summary>
 /// Creates a MO.
 /// <param name="message">The Message to which this Type belongs</param>
 /// <param name="description">The description of this type</param>
 ///</summary>
 public MO(IMessage message, string description)
     : base(message, description)
 {
     data = new IType[2];
     data[0] = new NM(message,"Quantity");
     data[1] = new ID(message, 0,"Denomination");
 }
Example #5
0
	///<summary>
	/// Creates a QSC.
	/// <param name="message">The Message to which this Type belongs</param>
	/// <param name="description">The description of this type</param>
	///</summary>
	public QSC(IMessage message, string description) : base(message, description){
		data = new IType[4];
		data[0] = new ST(message,"Name of field");
		data[1] = new ID(message, 0,"Relational operator");
		data[2] = new ST(message,"Value");
		data[3] = new ID(message, 0,"Relational conjunction");
	}
Example #6
0
        public static ITemplateInitializer GetInitializer(ID templateId)
        {
            ITemplateInitializer initializer;
            if (InitializerCache.TryGetValue(templateId, out initializer)) return initializer;

            return new StandardTemplateInitializer();
        }
Example #7
0
    private string GetCategories(string itemPath)
    {
      List<string> categories = new List<string>();
      Database db = Sitecore.Context.ContentDatabase ?? Sitecore.Context.Database;
      Item item = db.GetItem(itemPath);
      ID categoriesRootId = new ID("{41E44203-3CB9-45DD-8EED-9E36B5282D68}");
      string source = item.Fields[new ID("{0F347169-F131-4276-A69D-187C0CAC3740}")].Source;
      if (!string.IsNullOrEmpty(source))
      {
        var classificationSourceItems = LookupSources.GetItems(item, source);
        if ((classificationSourceItems != null) && (classificationSourceItems.Length>0))
        {
          Item taxonomies = classificationSourceItems.ToList().Find(sourceItem => sourceItem.Name.Equals("Taxonomies"));
          if (taxonomies != null)
          {
            categoriesRootId = taxonomies.ID;
          }
        }
      }

      Item categoriesRoot = db.GetItem(categoriesRootId);
      foreach (Item categoryGroupItem in categoriesRoot.Children)
      {
        categories.AddRange(GetCategories(categoryGroupItem.DisplayName, categoryGroupItem));
      }

      return string.Join("|", categories.ToArray());
    }
Example #8
0
	///<summary>
	/// Creates a SPD.
	/// <param name="message">The Message to which this Type belongs</param>
	/// <param name="description">The description of this type</param>
	///</summary>
	public SPD(IMessage message, string description) : base(message, description){
		data = new IType[4];
		data[0] = new ST(message,"Specialty Name");
		data[1] = new ST(message,"Governing Board");
		data[2] = new ID(message, 337,"Eligible or Certified");
		data[3] = new DT(message,"Date of Certification");
	}
        public BasicDataProvider3(string joinParentId)
        {
            Assert.ArgumentNotNull(joinParentId, "joinParentId");
            Assert.IsTrue(ID.IsID(joinParentId), "joinParentId must be a valid Sitecore ID");

            JoinParentId = new ID(joinParentId);

            Items = new Dictionary<ID, dynamic>()
                {
                    { GetIdForIdentifierString("one"), new
                        {
                            Name = "First item",
                            Fields = new Dictionary<ID,string>
                                {
                                    {_titleFieldId, "First item title"},
                                    {_textFieldId, "First item text"}
                                }
                        }},
                    { GetIdForIdentifierString("two"), new
                        {
                            Name = "Second item",
                            Fields = new Dictionary<ID,string>
                                {
                                    {_titleFieldId, "Second item title"},
                                    {_textFieldId, "Second item text"}
                                }
                        }}
                };
        }
Example #10
0
File: VH.cs Project: liddictm/nHapi
	///<summary>
	/// Creates a VH.
	/// <param name="message">The Message to which this Type belongs</param>
	/// <param name="description">The description of this type</param>
	///</summary>
	public VH(IMessage message, string description) : base(message, description){
		data = new IType[4];
		data[0] = new ID(message, 0,"Start day range");
		data[1] = new ID(message, 0,"End day range");
		data[2] = new TM(message,"Start hour range");
		data[3] = new TM(message,"End hour range");
	}
 public SectionInfo(string name, ID sectionId, ID templateId, int sectionSortOrder)
 {
     Name = name;
     SectionId = sectionId;
     TemplateId = templateId;
     SectionSortOrder = sectionSortOrder;
 }
        public void ItemSaved(object sender, EventArgs args)
        {
            var item = Event.ExtractParameter(args, 0) as Item;
            if (item != null && m_templateNames.Contains(item.TemplateName.ToLower()))
            {
                if (item.ID != m_processing && item.Paths.FullPath.ToLower().StartsWith(RootPath.ToLower()))
                {
                    if (string.IsNullOrEmpty(item["related pages"]))
                    {
                        var home = item.GetHomeByTraversal();
                        var relatedByTemplate = ItemReferences.GetItemsByTemplate(item.Template, home);
                        var relatedCount = relatedByTemplate.Count();

                        if (relatedCount > 0)
                        {
                            var random = new Random();
                            var select = new int[] { random.Next(0, relatedCount - 1), random.Next(0, relatedCount - 1), random.Next(0, relatedCount - 1) };

                            item.Editing.BeginEdit();

                            ((MultilistField)item.Fields["related pages"]).Add(relatedByTemplate.ElementAt(select[0]).ID.ToString());
                            ((MultilistField)item.Fields["related pages"]).Add(relatedByTemplate.ElementAt(select[1]).ID.ToString());
                            ((MultilistField)item.Fields["related pages"]).Add(relatedByTemplate.ElementAt(select[2]).ID.ToString());

                            m_processing = item.ID;
                            item.Editing.EndEdit();
                            m_processing = ID.Null;
                        }
                    }
                }
            }
        }
    protected string FindStandardValueInTheTemplate(DbTemplate template, ID fieldId)
    {
      if (template.StandardValues.ContainsKey(fieldId))
      {
        return template.StandardValues[fieldId].Value;
      }

      if (template.BaseIDs == null || template.BaseIDs.Length <= 0)
      {
        return null;
      }

      foreach (var baseId in template.BaseIDs)
      {
        if (ID.IsNullOrEmpty(baseId))
        {
          continue;
        }

        var baseTemplate = this.DataStorage.GetFakeTemplate(baseId);
        if (baseTemplate == null)
        {
          throw new TemplateNotFoundException("The template \"{0}\" was not found.".FormatWith(baseId.ToString()));
        }

        var value = this.FindStandardValueInTheTemplate(baseTemplate, fieldId);
        if (value != null)
        {
          return value;
        }
      }

      return null;
    }
Example #14
0
 /// <summary>
 /// Make a mesage to store the given data.
 /// </summary>
 /// <param name="nodeID">The sender identificator</param>
 /// <param name="request">The StoreResponse message that originated this message</param>
 /// <param name="theData">The CompleteTag to store</param>
 /// <param name="originalPublication">The publication datetime</param>
 /// <param name="nodeEndpoint">The sender node's kademlia address</param>
 /// <param name="transportUri">The sender node's transport uri</param>
 public StoreData(ID nodeID, StoreResponse request, CompleteTag theData, DateTime originalPublication, Uri nodeEndpoint, Uri transportUri)
     : base(nodeID, request, nodeEndpoint)
 {
     this.data = theData;
     this.publication = originalPublication;
     this.transportUri = transportUri;
 }
Example #15
0
        public static HtmlString BeginField(ID fieldId, Item item, object parameters)
        {
            Assert.ArgumentNotNull(fieldId, "fieldName");
            var renderFieldArgs = new RenderFieldArgs
            {
                Item = item,
                FieldName = item.Fields[fieldId].Name
            };
            if (parameters != null)
            {
                CopyProperties(parameters, renderFieldArgs);
                CopyProperties(parameters, renderFieldArgs.Parameters);
            }
            renderFieldArgs.Item = renderFieldArgs.Item ?? CurrentItem;

            if (renderFieldArgs.Item == null)
            {
                EndFieldStack.Push(string.Empty);
                return new HtmlString(string.Empty);
            }
            CorePipeline.Run("renderField", renderFieldArgs);
            var result1 = renderFieldArgs.Result;
            var str = result1.ValueOrDefault(result => result.FirstPart).OrEmpty();
            EndFieldStack.Push(result1.ValueOrDefault(result => result.LastPart).OrEmpty());
            return new HtmlString(str);
        }
 public void ShouldCreateTemplateFieldItemBasedOnDbField(ID templateId, DbField field)
 {
   using (var db = new Db { new DbTemplate(templateId) { field } })
   {
     db.GetItem(field.ID).Should().NotBeNull();
   }
 }
Example #17
0
	///<summary>
	/// Creates a CK.
	/// <param name="message">The Message to which this Type belongs</param>
	/// <param name="description">The description of this type</param>
	///</summary>
	public CK(IMessage message, string description) : base(message, description){
		data = new IType[4];
		data[0] = new NM(message,"ID number (NM)");
		data[1] = new ST(message,"Check digit");
		data[2] = new ID(message, 0,"Code identifying the check digit scheme employed");
		data[3] = new HD(message,"Assigning authority");
	}
        /// <summary>
        /// Move an item to a particular workflow state
        /// </summary>
        /// <param name="item">The item to go through workflow</param>
        /// <param name="workflowStateId">The ID of the workflow state</param>
        public void MoveToStateAndExecuteActions(Item item, ID workflowStateId)
        {
            IWorkflowProvider workflowProvider = item.Database.WorkflowProvider;
            IWorkflow workflow = workflowProvider.GetWorkflow(item);

            // if item is in any workflow
            if (workflow != null)
            {
                using (new EditContext(item))
                {
                    // update item's state to the new one
                    item[FieldIDs.WorkflowState] = workflowStateId.ToString();
                }

                Item stateItem = ItemManager.GetItem(workflowStateId, Language.Current, Version.Latest, item.Database, SecurityCheck.Disable);

                // if there are any actions for the new state
                if (!stateItem.HasChildren)
                    return;

                // TODO: Obsolete constructor
                var workflowPipelineArgs = new WorkflowPipelineArgs(item, string.Empty, null);

                // start executing the actions
                Pipeline pipeline = Pipeline.Start(stateItem, workflowPipelineArgs);
                if (pipeline == null)
                    return;

                // TODO: Obsolete class
                WorkflowCounters.ActionsExecuted.IncrementBy(pipeline.Processors.Count);
            }
        }
Example #19
0
    public virtual Item Create(string itemName, ID itemId, ID templateId, Database database, Item destination)
    {
      var language = Language.Current;

      if (this.DataStorage.GetFakeItem(itemId) != null)
      {
        return this.DataStorage.GetSitecoreItem(itemId, language);
      }

      var fieldList = this.DataStorage.GetFieldList(templateId, itemName);
      var item = ItemHelper.CreateInstance(itemName, itemId, templateId, fieldList, database, language);

      var parentItem = this.DataStorage.GetFakeItem(destination.ID);
      var fullPath = parentItem.FullPath + "/" + itemName;

      var dbitem = new DbItem(itemName, itemId, templateId) { ParentID = destination.ID, FullPath = fullPath };

      if (this.dataStorage.GetFakeTemplate(templateId) != null)
      {
        foreach (var field in this.dataStorage.GetFakeTemplate(templateId).Fields)
        {
          // TODO: Introduce field clonning.
          dbitem.Fields.Add(new DbField(field.Name) { ID = field.ID });
        }
      }

      this.DataStorage.FakeItems.Add(itemId, dbitem);
      this.DataStorage.GetFakeItem(destination.ID).Children.Add(dbitem);

      return item;
    }
Example #20
0
        public static EntryItem CreateNewEntry(BlogHomeItem blogItem, string name, string tags = null, ID[] categories = null, DateTime? entryDate = null)
        {
            using (new UserSwitcher("sitecore\\admin", true))
            {
                var entry = blogItem.InnerItem.Add(name, Constants.Templates.EntryTemplateId);

                if (tags != null)
                {
                    using (new EditContext(entry))
                    {
                        entry["Tags"] = tags;
                    }
                }

                if (categories != null)
                {
                    using (new EditContext(entry))
                    {
                        entry["Category"] = string.Join<ID>("|", categories);
                    }
                }

                if (entryDate != null)
                {
                    using (new EditContext(entry))
                    {
                        entry["Entry Date"] = DateUtil.ToIsoDate(entryDate.Value);
                    }
                }

                return entry;
            }
        }
Example #21
0
	///<summary>
	/// Creates a CK_ACCOUNT_NO.
	/// <param name="message">The Message to which this Type belongs</param>
	/// <param name="description">The description of this type</param>
	///</summary>
	public CK_ACCOUNT_NO(IMessage message, string description) : base(message, description){
		data = new IType[4];
		data[0] = new NM(message,"Account number");
		data[1] = new NM(message,"Check digit");
		data[2] = new ID(message, 0,"Check digit scheme");
		data[3] = new ID(message, 0,"Facility ID");
	}
		public static ControllerType GetControllerType(ID parentId, ID id)
		{
			ControllerType type;
			if (GetControllerIds(parentId.ToGuid()).TryGetValue(id.ToGuid(), out type))
				return type;
			return null;
		}
Example #23
0
        public static bool TriggerGoal(ID goalID)
        {
            if (goalID == (ID)null)
            {
                Log.Warn("GoalID is empty", typeof(AnalyticsHelper));
                return false;
            }

            if (!Tracker.IsActive)
            {
                Tracker.StartTracking();
            }

            if (Tracker.Current == null || Tracker.Current.Interaction == null || Tracker.Current.Interaction.CurrentPage == null)
            {
                Log.Warn("Tracker.Current == null || Tracker.Current.Interaction.CurrentPage == null", typeof(AnalyticsHelper));
                return false;
            }

            var goalItem = Sitecore.Context.Database.GetItem(goalID);
            if (goalItem == null)
            {
                Log.Warn("Goal Item is empty from ID: " + goalID, typeof(AnalyticsHelper));
                return false;
            }

            var goal = new PageEventItem(goalItem);
            Tracker.Current.Interaction.CurrentPage.Register(goal);
            return true;
        }
Example #24
0
File: PT.cs Project: snosrap/nhapi
 ///<summary>
 /// Creates a PT.
 /// <param name="message">The Message to which this Type belongs</param>
 /// <param name="description">The description of this type</param>
 ///</summary>
 public PT(IMessage message, string description)
     : base(message, description)
 {
     data = new IType[2];
     data[0] = new ID(message, 103,"Processing ID");
     data[1] = new ID(message, 207,"Processing Mode");
 }
        protected virtual void AddContactFacetMember(string facetName, ID parentId)
        {
            var contractType = ContactFacetHelper.GetContractTypeForFacet(facetName);

            foreach (string memberName in FacetReflectionUtil.NonFacetMemberNames(contractType))
            {
                var memberId = IDTableHelper.GenerateIdForFacetMember(memberName, parentId,
                    Sitecore.Strategy.Contacts.DataProviders.TemplateIDs.ContactFacetMemberTemplate);
                AddContactFacetMemberValues(facetName, memberName, memberId);
            }

            foreach (string memberName in FacetReflectionUtil.FacetMemberNames(contractType))
            {
                foreach (
                    string subMemberName in
                        FacetReflectionUtil.NonFacetMemberNames(contractType.GetProperty(memberName).PropertyType))
                {
                    string key = $"{memberName}{NestedFacets.Delimeter}{subMemberName}";

                    var memberId = IDTableHelper.GenerateIdForFacetMember(key, parentId,
                        Sitecore.Strategy.Contacts.DataProviders.TemplateIDs.ContactFacetMemberTemplate);
                    AddContactFacetMemberValues(facetName, key, memberId);
                }
            }
        }
Example #26
0
		public SyncItem GetItem(ID id)
		{
			Assert.ArgumentNotNull(id, "id");

			SyncItem resultItem;
			if (!_idLookup.TryGetValue(id, out resultItem))
			{
				lock (_idLookupLock)
				{
					if (!_idLookup.TryGetValue(id, out resultItem))
					{
						string stringId = id.ToString();
						SyncItem item = _innerItems.Find(x => x.ID == stringId);
						if (item != null)
						{
							_idLookup.Add(id, item);
						}

						return item;
					}
				}
			}

			return resultItem;
		}
Example #27
0
File: RP.cs Project: liddictm/nHapi
	///<summary>
	/// Creates a RP.
	/// <param name="message">The Message to which this Type belongs</param>
	/// <param name="description">The description of this type</param>
	///</summary>
	public RP(IMessage message, string description) : base(message, description){
		data = new IType[4];
		data[0] = new ST(message,"Pointer");
		data[1] = new HD(message,"Application ID");
		data[2] = new ID(message, 0,"Type of data");
		data[3] = new ID(message, 0,"Subtype");
	}
Example #28
0
File: EI.cs Project: liddictm/nHapi
	///<summary>
	/// Creates a EI.
	/// <param name="message">The Message to which this Type belongs</param>
	/// <param name="description">The description of this type</param>
	///</summary>
	public EI(IMessage message, string description) : base(message, description){
		data = new IType[4];
		data[0] = new ST(message,"Entity identifier");
		data[1] = new IS(message, 300,"Namespace ID");
		data[2] = new ST(message,"Universal ID");
		data[3] = new ID(message, 301,"Universal ID type");
	}
    public JsonItem()
    {
      this.ID = ID.Null;
      this.ParentID = ID.Null;

      JsonDataProvider.InitializeDefaultValues(this.Fields);
    }
    private static void DeserializeTemplate(DataStorage dataStorage, ID templateId, string serializationFolderName)
    {
      var filePath = templateId.FindFilePath(serializationFolderName);

      if (string.IsNullOrWhiteSpace(filePath) || !File.Exists(filePath))
      {
        return;
      }


      var dsDbTemplate = new DsDbTemplate(templateId, serializationFolderName);

      dataStorage.AddFakeItem(dsDbTemplate);

      // Deserialize base templates
      var baseTemplatesField = dsDbTemplate.Fields.FirstOrDefault(f => f.ID == FieldIDs.BaseTemplate);

      if (baseTemplatesField == null || string.IsNullOrWhiteSpace(baseTemplatesField.Value))
      {
        return;
      }

      foreach (var baseTemplateId in baseTemplatesField.Value.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries)
        .Where(ID.IsID)
        .Select(ID.Parse)
        .Where(baseTemplateId => dataStorage.GetFakeItem(baseTemplateId) == null))
      {
        DeserializeTemplate(dataStorage, baseTemplateId, dsDbTemplate.SerializationFolderName);
      }
    }
Example #31
0
 public override string tv()
 {
     return(ID.ToString() + ", " + Firm.ToString() + ", " + Material.ToString() + ", " + Price.ToString() + ", " + Release_data.ToString("dd MMMM yyyy"));
 }
        public virtual string GetPropertyValue(Guid id)
        {
            var sitecoreId = new ID(id);

            return(_item[sitecoreId]);
        }
        public virtual ISitecoreField GetField(Guid id)
        {
            var sitecoreId = new ID(id);

            return(CreateSitecoreField(_item.Fields[sitecoreId]));
        }
Example #34
0
 public void WriteEntry(string message, EventLogEntryType type, ID eventID)
 {
     base.WriteEntry(message, type, (int)eventID);
 }
 public static CustomerNameChanged Build(ID customerID, PersonName name)
 {
     return(new CustomerNameChanged(customerID, name));
 }
 private CustomerNameChanged(ID customerID, PersonName name)
 {
     CustomerId = customerID;
     Name       = name;
 }
Example #37
0
 public override int GetHashCode()
 {
     return(ID.GetHashCode());
 }
 private Person GetPersonById(Guid personId)
 {
     return(GetAllPersons().FirstOrDefault(i => i.ID == ID.Parse(personId)));
 }
Example #39
0
 public override string Print_Mem_Data()
 {
     return(ID.ToString() + " " + Name + " Sales:" + Sales);
 }
Example #40
0
 public override string ToString()
 {
     return(ID.ToString());
 }
Example #41
0
        public override bool Equals(object obj)
        {
            var a = obj as IUserAccount;

            return(a != null && ID.Equals(a.ID));
        }
Example #42
0
 protected abstract AsyncServerStreamingCall<TState> GetUpdatesCall(TClient client, ID id, CancellationToken token);
Example #43
0
 /// <summary>
 /// Removes information about a specific item from database caches. This compensates
 /// cache functionality that depends on database events (which are disabled when loading).
 /// </summary>
 /// <param name="database">Database to clear caches for.</param>
 /// <param name="itemId">Item ID to remove</param>
 protected virtual void ClearCaches(Database database, ID itemId)
 {
     database.Caches.ItemCache.RemoveItem(itemId);
     database.Caches.DataCache.RemoveItemInformation(itemId);
 }
Example #44
0
 public UpdateExpPacket(int exp, ID packetID)
 {
     this.name = (int)packetID;
     this.exp  = exp;
 }
Example #45
0
        public static async Task <bool> CanRunRPC(TextBox tbText1, TextBox tbText2, TextBox tbSmallText,
                                                  TextBox tbLargeText, TextBox tbClientID = null, bool tokenTextChanged = false)
        {
            var isEnabled = true;

            if (tbText2.Text.Length == 1)
            {
                tbText2.SetResourceReference(Control.BorderBrushProperty, "Red");
                tbText2.ToolTip = new ToolTip(App.Text.LengthMustBeAtLeast2CharactersLong);
                isEnabled       = false;
            }
            else
            {
                tbText2.SetResourceReference(Control.BorderBrushProperty, "AccentColour4SCBrush");
                tbText2.ToolTip = null;
            }

            if (tbText1.Text.Length == 1)
            {
                tbText1.SetResourceReference(Control.BorderBrushProperty, "Red");
                tbText1.ToolTip = new ToolTip(App.Text.LengthMustBeAtLeast2CharactersLong);
                isEnabled       = false;
            }
            else
            {
                tbText1.SetResourceReference(Control.BorderBrushProperty, "AccentColour4SCBrush");
                tbText1.ToolTip = null;
            }

            if (tbSmallText.Text.Length == 1)
            {
                tbSmallText.SetResourceReference(Control.BorderBrushProperty, "Red");
                tbSmallText.ToolTip = new ToolTip(App.Text.LengthMustBeAtLeast2CharactersLong);
                isEnabled           = false;
            }
            else
            {
                tbSmallText.SetResourceReference(Control.BorderBrushProperty, "AccentColour4SCBrush");
                tbSmallText.ToolTip = null;
            }

            if (tbLargeText.Text.Length == 1)
            {
                tbLargeText.SetResourceReference(Control.BorderBrushProperty, "Red");
                tbLargeText.ToolTip = new ToolTip(App.Text.LengthMustBeAtLeast2CharactersLong);
                isEnabled           = false;
            }
            else
            {
                tbLargeText.SetResourceReference(Control.BorderBrushProperty, "AccentColour4SCBrush");
                tbLargeText.ToolTip = null;
            }

            var profile = MasterCustomPage.Profiles != null && MasterCustomPage.CurrentButton != null
                ? MasterCustomPage.Profiles[MasterCustomPage.CurrentButton.Content.ToString()]
                : null;

            if (OnCustomPage && profile != null)
            {
                if (!RPC.IsRPCRunning)
                {
                    MainPage._MainPage.btnUpdate.IsEnabled = false;
                    MainPage._MainPage.btnStart.IsEnabled  = false;
                }

                var isValidCode =
                    ulong.TryParse(tbClientID.Text, NumberStyles.Any, new NumberFormatInfo(), out var ID);

                if (App.Config.CheckToken && tokenTextChanged)
                {
                    if (ID.ToString().Length != tbClientID.MaxLength || !isValidCode)
                    {
                        RPC.IDToUse = 0;
                        tbClientID.SetResourceReference(Control.BorderBrushProperty, "Red");
                        tbClientID.ToolTip = !isValidCode
                            ? new ToolTip(App.Text.ClientIDIsNotValid)
                            : new ToolTip(App.Text.ClientIDMustBe18CharactersLong);
                        isEnabled = false;
                    }
                    else
                    {
                        tbClientID.SetResourceReference(Control.BorderBrushProperty, "Orange");
                        tbClientID.ToolTip = new ToolTip(App.Text.CheckingClientID);
                        await Task.Delay(1000);

                        HttpResponseMessage T = null;
                        try
                        {
                            var Client = new HttpClient();
                            T = await Client.PostAsync("https://discordapp.com/api/oauth2/token/rpc",
                                                       new FormUrlEncodedContent(new Dictionary <string, string>
                            {
                                { "client_id", ID.ToString() }
                            }));
                        }
                        catch
                        {
                            if (MainPage._MainPage.frmContent.Content is MasterCustomPage && RPC.Type == RPC.RPCType.Custom)
                            {
                                App.Logging.Error("API", App.Text.DiscordAPIDown);
                                tbClientID.ToolTip = new ToolTip($"{App.Text.NetworkIssue}!");
                                tbClientID.SetResourceReference(Control.BorderBrushProperty, "Red");
                                isEnabled = false;
                            }
                        }

                        if (MainPage._MainPage.frmContent.Content is MasterCustomPage && RPC.Type == RPC.RPCType.Custom &&
                            T != null && profile.ClientID ==
                            MasterCustomPage.Profiles[MasterCustomPage.CurrentButton.Content.ToString()].ClientID)
                        {
                            if (T.StatusCode == HttpStatusCode.BadRequest)
                            {
                                App.Logging.Error("API", App.Text.ClientIDIsNotValid);
                                tbClientID.ToolTip = new ToolTip(App.Text.ClientIDIsNotValid);
                                tbClientID.SetResourceReference(Control.BorderBrushProperty, "Red");
                                isEnabled = false;
                            }
                            else if (T.StatusCode != HttpStatusCode.Unauthorized)
                            {
                                var response = T.Content.ReadAsStringAsync().GetAwaiter().GetResult();
                                App.Logging.Error("API", $"{App.Text.APIError} {response}");
                                tbClientID.ToolTip = new ToolTip($"{App.Text.APIIssue}!");
                                tbClientID.SetResourceReference(Control.BorderBrushProperty, "Red");
                                isEnabled = false;
                            }
                            else
                            {
                                if (MainPage._MainPage.frmContent.Content is MasterCustomPage)
                                {
                                    RPC.IDToUse = ID;
                                }

                                tbClientID.SetResourceReference(Control.BorderBrushProperty, "AccentColour4SCBrush");
                                tbClientID.ToolTip = null;
                            }
                        }
                    }
                }
                else if (MainPage._MainPage.frmContent.Content is MasterCustomPage)
                {
                    if (tokenTextChanged)
                    {
                        RPC.IDToUse = ID;
                        tbClientID.SetResourceReference(Control.BorderBrushProperty, "AccentColour4SCBrush");
                        tbClientID.ToolTip = null;
                    }
                    else if (tbClientID.BorderBrush == Application.Current.Resources["Red"])
                    {
                        isEnabled = false;
                    }
                }
            }

            if (MainPage._MainPage.frmContent.Content is MultiRPCPage && RPC.Type == RPC.RPCType.MultiRPC ||
                OnCustomPage && MasterCustomPage.Profiles[MasterCustomPage.CurrentButton.Content.ToString()] == profile && !RPC.AFK)
            {
                if (MainPage._MainPage.btnStart.Content.ToString() == App.Text.Shutdown)
                {
                    MainPage._MainPage.btnUpdate.IsEnabled = isEnabled;
                    MainPage._MainPage.btnStart.IsEnabled  = true;
                }
                else
                {
                    MainPage._MainPage.btnUpdate.IsEnabled = false;
                    MainPage._MainPage.btnStart.IsEnabled  = isEnabled;
                }
            }

            return(isEnabled);
        }
Example #46
0
        /// <summary>
        /// Pastes SyncItem into the database.
        ///
        /// </summary>
        /// <param name="syncItem">The sync item.</param>
        /// <param name="ignoreMissingTemplateFields">Whether to ignore fields in the serialized item that do not exist on the Sitecore template</param>
        /// <returns>
        /// The pasted item.
        /// </returns>
        /// <exception cref="T:Sitecore.Data.Serialization.Exceptions.ParentItemNotFoundException"><c>ParentItemNotFoundException</c>.</exception><exception cref="T:System.Exception"><c>Exception</c>.</exception><exception cref="T:Sitecore.Data.Serialization.Exceptions.ParentForMovedItemNotFoundException"><c>ParentForMovedItemNotFoundException</c>.</exception>
        public override ISourceItem Deserialize(ISerializedItem serializedItem, bool ignoreMissingTemplateFields)
        {
            Assert.ArgumentNotNull(serializedItem, "serializedItem");

            var typed = serializedItem as SitecoreSerializedItem;

            if (typed == null)
            {
                throw new ArgumentException("Serialized item must be a SitecoreSerializedItem", "serializedItem");
            }

            var syncItem = typed.InnerItem;

            Database database = Factory.GetDatabase(syncItem.DatabaseName);

            Item destinationParentItem = database.GetItem(syncItem.ParentID);
            ID   itemId            = ID.Parse(syncItem.ID);
            Item targetItem        = database.GetItem(itemId);
            bool newItemWasCreated = false;

            // the target item did not yet exist, so we need to start by creating it
            if (targetItem == null)
            {
                targetItem = CreateTargetItem(syncItem, destinationParentItem);

                _logger.CreatedNewItem(targetItem);

                newItemWasCreated = true;
            }
            else
            {
                // check if the parent of the serialized item does not exist
                // which, since the target item is known to exist, means that
                // the serialized item was moved but its new parent item does
                // not exist to paste it under
                if (destinationParentItem == null)
                {
                    throw new ParentForMovedItemNotFoundException
                          {
                              ParentID = syncItem.ParentID,
                              Item     = targetItem
                          };
                }

                // if the parent IDs mismatch that means we need to move the existing
                // target item to its new parent from the serialized item
                if (destinationParentItem.ID != targetItem.ParentID)
                {
                    var oldParent = targetItem.Parent;
                    targetItem.MoveTo(destinationParentItem);
                    _logger.MovedItemToNewParent(destinationParentItem, oldParent, targetItem);
                }
            }
            try
            {
                ChangeTemplateIfNeeded(syncItem, targetItem);
                RenameIfNeeded(syncItem, targetItem);
                ResetTemplateEngineIfItemIsTemplate(targetItem);

                using (new EditContext(targetItem))
                {
                    targetItem.RuntimeSettings.ReadOnlyStatistics = true;
                    targetItem.RuntimeSettings.SaveAll            = true;

                    foreach (Field field in targetItem.Fields)
                    {
                        if (field.Shared && syncItem.SharedFields.All(x => x.FieldID != field.ID.ToString()))
                        {
                            _logger.ResetFieldThatDidNotExistInSerialized(field);
                            field.Reset();
                        }
                    }

                    foreach (SyncField field in syncItem.SharedFields)
                    {
                        PasteSyncField(targetItem, field, ignoreMissingTemplateFields, newItemWasCreated);
                    }
                }

                ClearCaches(database, itemId);
                targetItem.Reload();
                ResetTemplateEngineIfItemIsTemplate(targetItem);

                Hashtable versionTable = CommonUtils.CreateCIHashtable();

                // this version table allows us to detect and remove orphaned versions that are not in the
                // serialized version, but are in the database version
                foreach (Item version in targetItem.Versions.GetVersions(true))
                {
                    versionTable[version.Uri] = null;
                }

                foreach (SyncVersion syncVersion in syncItem.Versions)
                {
                    var version = PasteSyncVersion(targetItem, syncVersion, ignoreMissingTemplateFields, newItemWasCreated);
                    if (versionTable.ContainsKey(version.Uri))
                    {
                        versionTable.Remove(version.Uri);
                    }
                }

                foreach (ItemUri uri in versionTable.Keys)
                {
                    var versionToRemove = Database.GetItem(uri);

                    _logger.RemovingOrphanedVersion(versionToRemove);

                    versionToRemove.Versions.RemoveVersion();
                }

                ClearCaches(targetItem.Database, targetItem.ID);

                return(new SitecoreSourceItem(targetItem));
            }
            catch (ParentForMovedItemNotFoundException)
            {
                throw;
            }
            catch (ParentItemNotFoundException)
            {
                throw;
            }
#if SITECORE_7
            catch (FieldIsMissingFromTemplateException)
            {
                throw;
            }
#endif
            catch (Exception ex)
            {
                if (newItemWasCreated)
                {
                    targetItem.Delete();
                    ClearCaches(database, itemId);
                }
                throw new Exception("Failed to paste item: " + syncItem.ItemPath, ex);
            }
        }
Example #47
0
 public ReferenceFieldProxy(Item item, ID fieldID) : base(item, fieldID)
 {
 }
Example #48
0
        /// <summary>
        /// Pastes single version from ItemDom into the item
        ///
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="syncVersion">The sync version.</param>
        /// <param name="ignoreMissingTemplateFields">Whether to ignore fields in the serialized item that do not exist on the Sitecore template</param>
        /// <param name="creatingNewItem">Whether the item under update is new or not (controls logging verbosity)</param>
        /// <returns>The version that was pasted</returns>
        protected virtual Item PasteSyncVersion(Item item, SyncVersion syncVersion, bool ignoreMissingTemplateFields, bool creatingNewItem)
        {
            Language language            = Language.Parse(syncVersion.Language);
            var      targetVersion       = global::Sitecore.Data.Version.Parse(syncVersion.Version);
            Item     languageItem        = item.Database.GetItem(item.ID, language);
            Item     languageVersionItem = languageItem.Versions[targetVersion];

            if (languageVersionItem == null)
            {
                languageVersionItem = languageItem.Versions.AddVersion();
                if (!creatingNewItem)
                {
                    _logger.AddedNewVersion(languageVersionItem);
                }
            }

            // ReSharper disable once SimplifyLinqExpression
            if (!languageVersionItem.Versions.GetVersionNumbers().Any(x => x.Number == languageVersionItem.Version.Number))
            {
                if (!creatingNewItem)
                {
                    _logger.AddedNewVersion(languageVersionItem);
                }
            }

            using (new EditContext(languageVersionItem))
            {
                languageVersionItem.RuntimeSettings.ReadOnlyStatistics = true;

                if (languageVersionItem.Versions.Count == 0)
                {
                    languageVersionItem.Fields.ReadAll();
                }

                foreach (Field field in languageVersionItem.Fields)
                {
                    if (!field.Shared && syncVersion.Fields.All(x => x.FieldID != field.ID.ToString()))
                    {
                        _logger.ResetFieldThatDidNotExistInSerialized(field);
                        field.Reset();
                    }
                }

                bool wasOwnerFieldParsed = false;
                foreach (SyncField field in syncVersion.Fields)
                {
                    ID result;
                    if (ID.TryParse(field.FieldID, out result) && result == FieldIDs.Owner)
                    {
                        wasOwnerFieldParsed = true;
                    }

                    PasteSyncField(languageVersionItem, field, ignoreMissingTemplateFields, creatingNewItem);
                }

                if (!wasOwnerFieldParsed)
                {
                    languageVersionItem.Fields[FieldIDs.Owner].Reset();
                }
            }

            ClearCaches(languageVersionItem.Database, languageVersionItem.ID);
            ResetTemplateEngineIfItemIsTemplate(languageVersionItem);

            return(languageVersionItem);
        }
Example #49
0
 public static bool IsExist(ExportOperationType type, Item accountItem, ID fieldId, string fieldValue)
 {
     return(Provider.IsExist(type, accountItem, fieldId, fieldValue));
 }
Example #50
0
 public int CompareTo(App other)
 {
     return(ID.CompareTo(other.ID));
 }
        /// <summary>
        /// Sets the field.
        /// </summary>
        /// <param name="field">The field.</param>
        /// <param name="value">The value.</param>
        /// <param name="config">The config.</param>
        /// <param name="context">The context.</param>
        /// <exception cref="Glass.Mapper.MapperException">
        /// No item with ID {0}. Can not update Link linkField.Formatted(newId)
        /// or
        /// No item with ID {0}. Can not update Link linkField.Formatted(newId)
        /// </exception>
        public override void SetField(Field field, object value, SitecoreFieldConfiguration config, SitecoreDataMappingContext context)
        {
            Link link = value as Link;


            if (field == null)
            {
                return;
            }

            var item = field.Item;

            LinkField linkField = new LinkField(field);

            if (link == null || link.Type == LinkType.NotSet)
            {
                linkField.Clear();
                return;
            }


            switch (link.Type)
            {
            case LinkType.Internal:
                linkField.LinkType = "internal";
                if (linkField.TargetID.Guid != link.TargetId)
                {
                    if (link.TargetId == Guid.Empty)
                    {
                        ItemLink iLink = new ItemLink(item.Database.Name, item.ID, linkField.InnerField.ID, linkField.TargetItem.Database.Name, linkField.TargetID, linkField.TargetItem.Paths.FullPath);
                        linkField.RemoveLink(iLink);
                    }
                    else
                    {
                        ID   newId  = new ID(link.TargetId);
                        Item target = item.Database.GetItem(newId);
                        if (target != null)
                        {
                            linkField.TargetID = newId;
                            ItemLink nLink = new ItemLink(item.Database.Name, item.ID, linkField.InnerField.ID, target.Database.Name, target.ID, target.Paths.FullPath);
                            linkField.UpdateLink(nLink);
                            linkField.Url = LinkManager.GetItemUrl(target);
                        }
                        else
                        {
                            throw new MapperException("No item with ID {0}. Can not update Link linkField".Formatted(newId));
                        }
                    }
                }
                break;

            case LinkType.Media:
                linkField.LinkType = "media";
                if (linkField.TargetID.Guid != link.TargetId)
                {
                    if (link.TargetId == Guid.Empty)
                    {
                        ItemLink iLink = new ItemLink(item.Database.Name, item.ID, linkField.InnerField.ID, linkField.TargetItem.Database.Name, linkField.TargetID, linkField.TargetItem.Paths.FullPath);
                        linkField.RemoveLink(iLink);
                    }
                    else
                    {
                        ID   newId  = new ID(link.TargetId);
                        Item target = item.Database.GetItem(newId);

                        if (target != null)
                        {
                            global::Sitecore.Data.Items.MediaItem media = new global::Sitecore.Data.Items.MediaItem(target);

                            linkField.TargetID = newId;
                            ItemLink nLink = new ItemLink(item.Database.Name, item.ID, linkField.InnerField.ID, target.Database.Name, target.ID, target.Paths.FullPath);
                            linkField.UpdateLink(nLink);
                            linkField.Url = global::Sitecore.Resources.Media.MediaManager.GetMediaUrl(media);
                        }
                        else
                        {
                            throw new MapperException("No item with ID {0}. Can not update Link linkField".Formatted(newId));
                        }
                    }
                }
                break;

            case LinkType.External:
                linkField.LinkType = "external";
                linkField.Url      = link.Url;
                break;

            case LinkType.Anchor:
                linkField.LinkType = "anchor";
                linkField.Url      = link.Anchor;
                break;

            case LinkType.MailTo:
                linkField.LinkType = "mailto";
                linkField.Url      = link.Url;
                break;

            case LinkType.JavaScript:
                linkField.LinkType = "javascript";
                linkField.Url      = link.Url;
                break;
            }



            if (!link.Anchor.IsNullOrEmpty())
            {
                linkField.Anchor = link.Anchor;
            }
            if (!link.Class.IsNullOrEmpty())
            {
                linkField.Class = link.Class;
            }
            if (!link.Text.IsNullOrEmpty())
            {
                linkField.Text = link.Text;
            }
            if (!link.Title.IsNullOrEmpty())
            {
                linkField.Title = link.Title;
            }
            if (!link.Query.IsNullOrEmpty())
            {
                linkField.QueryString = link.Query;
            }
            if (!link.Target.IsNullOrEmpty())
            {
                linkField.Target = link.Target;
            }
        }
 /// <summary>
 /// Packs this message into an object array that can be used to send the message to other GameObjects.
 /// </summary>
 /// <returns></returns>
 public object[] ToObjects()
 {
     return new object[] { Source, Name, ID.ToByteArray(), (int)Type, Payload, Error };
 }
 protected virtual List <string> GetValues(Field field, ID selectFieldId)
 {
     return(Enumerable.ToList <string>(Enumerable.Select <Item, string>((IEnumerable <Item>)((MultilistField)field).GetItems(), (Func <Item, string>)(i => i[selectFieldId]))));
 }
Example #54
0
 public static bool IsExist(Item accountItem, ID fieldId, string fieldValue)
 {
     return(Provider.IsExist(accountItem, fieldId, fieldValue));
 }
Example #55
0
        /// <summary>
        /// toolbar事件
        /// 作者:姚东
        /// 时间:20100919
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void toolbar_MenuItemClick(object sender, MenuEventArgs e)
        {
            int    count         = 0;
            int    num           = 0;
            string AnswerGuid    = "";
            string ApprovalStaus = "0";
            string par           = "";
            string SID;
            string UID            = "";
            string AnswerUserKind = "";

            SID = (Request.QueryString["SID"]).ToString();
            switch (e.Item.Value)
            {
            case "Delete":
                for (int i = 0; i < grid.Rows.Count; i++)
                {
                    CheckBox chkItem = (CheckBox)grid.Rows[i].FindControl("chkItem");
                    if (chkItem != null && chkItem.Checked == true)
                    {
                        count++;
                        AnswerGuid = ConvertString(grid.DataKeys[i]["AnswerGUID"]);
                        //new AnswerManager_Layer().DeleteAnswer(AnswerGuid);
                        int ReturnNum = new AnswerManager_Layer().SetApprovalStaus("3", AnswerGuid);
                        new AnswerManager_Layer().UpdateAnswerNum(ReturnNum, ID.ToString());

                        num++;
                    }
                }
                new AnswerManager_Layer().UpdateAnswerNum(num, SID);
                if (count == this.grid.Rows.Count)
                {
                    viewpage1.CurrentPageIndex = viewpage1.CurrentPageIndex == 1 ? 1 : viewpage1.CurrentPageIndex - 1;
                }
                BindGridView();
                PageHelper.ShowMessage("删除成功!");
                break;

            case "Pass":
                num = 0;
                try
                {
                    par = ConvertString(new AnswerManager_Layer().GetSparBySID(SID).Rows[0]["Par"]);
                }
                catch (Exception ex)
                {
                }

                if (par.IndexOf("|NeedConfirm:1") > 0)
                {
                    for (int i = 0; i < grid.Rows.Count; i++)
                    {
                        UID            = ConvertString(grid.DataKeys[i]["UID"]);
                        AnswerUserKind = ConvertString(grid.DataKeys[i]["AnswerUserKind"]);
                        CheckBox chkItem = (CheckBox)grid.Rows[i].FindControl("chkItem");
                        if (chkItem != null && chkItem.Checked == true)
                        {
                            count++;
                            AnswerGuid    = ConvertString(grid.DataKeys[i]["AnswerGUID"]);
                            ApprovalStaus = ConvertString(grid.DataKeys[i]["ApprovalStaus"]);
                            if (ApprovalStaus == "0")
                            {
                                new AnswerManager_Layer().SetApprovalStaus("1", AnswerGuid);
                                if (AnswerUserKind != "1" && AnswerUserKind != "2")
                                {
                                    string TabelName = null;
                                    string UserGuid  = null; //会员GUID
                                    string prefix    = new Survey_ss_Layer().prefix;
                                    int    integral  = 0;    //积分
                                    UserGuid = ConvertString(new Survey_ss_Layer().GetUserGUID(UID.ToString()).Rows[0]["id"]);
                                    integral = int.Parse(ConvertString(new Survey_ss_Layer().GetSIntegral(SID).Rows[0]["Point"]));
                                    string        sqlUpdatePoint = "";
                                    SqlDataReader dr             = new Survey_ss_Layer().GetHuiYuan_Point(UserGuid);


                                    TabelName = " " + prefix + "HuiYuan_Point ";

                                    if (!dr.Read())
                                    {
                                        sqlUpdatePoint = "Insert into" + TabelName + "(HuiYuanGuid,TotalPoint,RemainPoint,Status) values(@HuiYuanGuid,@integral,@integral,1)";
                                    }
                                    else
                                    {
                                        sqlUpdatePoint = "Update" + TabelName + "set TotalPoint=TotalPoint+@integral,RemainPoint=RemainPoint+@integral where HuiYuanGuid=@HuiYuanGuid";
                                    }

                                    SqlParameter[] parameters = new SqlParameter[2];
                                    parameters[0] = new SqlParameter("@integral", integral);
                                    parameters[1] = new SqlParameter("@HuiYuanGuid", UserGuid);

                                    new AnswerManager_Layer().ExcuteSql(sqlUpdatePoint, parameters);
                                }
                                num++;
                            }
                            else
                            {
                                continue;
                            }
                        }
                    }
                    if (count == this.grid.Rows.Count)
                    {
                        viewpage1.CurrentPageIndex = viewpage1.CurrentPageIndex == 1 ? 1 : viewpage1.CurrentPageIndex - 1;
                    }
                    BindGridView();
                    if (num == 0)
                    {
                        PageHelper.ShowMessage("所选项目不可审核!");
                    }
                    else
                    {
                        PageHelper.ShowMessage("审批通过成功!");
                    }
                }
                else
                {
                    if (count == this.grid.Rows.Count)
                    {
                        viewpage1.CurrentPageIndex = viewpage1.CurrentPageIndex == 1 ? 1 : viewpage1.CurrentPageIndex - 1;
                    }
                    BindGridView();

                    PageHelper.ShowMessage("此份问卷答卷无需审批!");
                }

                break;

            case "Invalid":
                num        = 0;
                AnswerGuid = "";
                try
                {
                    par = ConvertString(new AnswerManager_Layer().GetSparBySID(SID).Rows[0]["Par"]);
                }
                catch (Exception ex)
                {
                }

                if (par.IndexOf("|NeedConfirm:1") > 0)
                {
                    for (int i = 0; i < grid.Rows.Count; i++)
                    {
                        CheckBox chkItem = (CheckBox)grid.Rows[i].FindControl("chkItem");
                        if (chkItem != null && chkItem.Checked == true)
                        {
                            count++;
                            AnswerGuid    = ConvertString(grid.DataKeys[i]["AnswerGUID"]);
                            ApprovalStaus = ConvertString(grid.DataKeys[i]["ApprovalStaus"]);

                            if (ApprovalStaus == "0")
                            {
                                int ReturnNum = new AnswerManager_Layer().SetApprovalStaus("2", AnswerGuid);
                                new AnswerManager_Layer().UpdateAnswerNum(ReturnNum, ID.ToString());
                                num++;
                            }
                            else
                            {
                                continue;
                            }
                        }
                    }
                    if (count == this.grid.Rows.Count)
                    {
                        viewpage1.CurrentPageIndex = viewpage1.CurrentPageIndex == 1 ? 1 : viewpage1.CurrentPageIndex - 1;
                    }
                    BindGridView();

                    if (num == 0)
                    {
                        PageHelper.ShowMessage("所选项目不可审核!");
                    }
                    else
                    {
                        PageHelper.ShowMessage("审批作废成功!");
                    }
                }
                else
                {
                    if (count == this.grid.Rows.Count)
                    {
                        viewpage1.CurrentPageIndex = viewpage1.CurrentPageIndex == 1 ? 1 : viewpage1.CurrentPageIndex - 1;
                    }
                    BindGridView();

                    PageHelper.ShowMessage("此份问卷答卷无需审批!");
                }
                break;
            }
        }
Example #56
0
        /// <summary>
        /// Generates an Initializer class (a proxy that allows us to quickly construct instances of a strongly typed item wrapper without resorting to reflection)
        /// </summary>
        private void CreateInitializer(CodeNamespace templateNamespace, CodeTypeDeclaration concrete, ID templateId)
        {
            CodeTypeDeclaration initializer = templateNamespace.CreateType(MemberAttributes.Public, concrete.Name + "Initializer");

            // ReSharper disable BitwiseOperatorOnEnumWithoutFlags
            initializer.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            // ReSharper restore BitwiseOperatorOnEnumWithoutFlags
            initializer.BaseTypes.Add(typeof(ITemplateInitializer));
            AddGeneratedCodeAttributeToType(initializer);

            var templateIdProperty = new CodeMemberProperty
            {
                // ReSharper disable BitwiseOperatorOnEnumWithoutFlags
                Attributes = MemberAttributes.Public | MemberAttributes.Final,
                // ReSharper restore BitwiseOperatorOnEnumWithoutFlags
                Type = new CodeTypeReference(typeof(ID)),
                Name = "InitializesTemplateId"
            };

            // all this for return new ID("xxxxx"); lol
            templateIdProperty.GetStatements.Add(new CodeMethodReturnStatement(new CodeObjectCreateExpression(typeof(ID), new CodeSnippetExpression("\"" + templateId + "\""))));

            initializer.Members.Add(templateIdProperty);

            var initializerItemMethod = new CodeMemberMethod
            {
                Name = "CreateInstance",
                // ReSharper disable BitwiseOperatorOnEnumWithoutFlags
                Attributes = MemberAttributes.Public | MemberAttributes.Final,
                // ReSharper restore BitwiseOperatorOnEnumWithoutFlags
                ReturnType = new CodeTypeReference(typeof(IStandardTemplateItem))
            };

            initializerItemMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(Item), "innerItem"));

            // all this for return new ConcreteType(innerItem); lol
            initializerItemMethod.Statements.Add(new CodeMethodReturnStatement(new CodeObjectCreateExpression(new CodeTypeReference(concrete.Name), new CodeVariableReferenceExpression("innerItem"))));

            initializer.Members.Add(initializerItemMethod);

            var initializerIndexMethod = new CodeMemberMethod
            {
                Name = "CreateInstanceFromSearch",
                // ReSharper disable BitwiseOperatorOnEnumWithoutFlags
                Attributes = MemberAttributes.Public | MemberAttributes.Final,
                // ReSharper restore BitwiseOperatorOnEnumWithoutFlags
                ReturnType = new CodeTypeReference(typeof(IStandardTemplateItem))
            };

            initializerIndexMethod.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(IDictionary <string, string>), CodeTypeReferenceOptions.GlobalReference), "searchFields"));

            // all this for return new ConcreteType(searchFields); lol
            initializerIndexMethod.Statements.Add(new CodeMethodReturnStatement(new CodeObjectCreateExpression(new CodeTypeReference(concrete.Name), new CodeVariableReferenceExpression("searchFields"))));

            initializer.Members.Add(initializerIndexMethod);
        }
        public static Item TargetItem(this Item item, ID linkFieldId)
        {
            var linkField = (LinkField)item?.Fields?[linkFieldId];

            return(linkField?.TargetItem);
        }
Example #58
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (ID != 0L)
            {
                hash ^= ID.GetHashCode();
            }
            if (CommandType != 0)
            {
                hash ^= CommandType.GetHashCode();
            }
            if (MoveDirection != 0)
            {
                hash ^= MoveDirection.GetHashCode();
            }
            if (MoveDuration != 0)
            {
                hash ^= MoveDuration.GetHashCode();
            }
            if (ThrowDistance != 0D)
            {
                hash ^= pbc::ProtobufEqualityComparers.BitwiseDoubleEqualityComparer.GetHashCode(ThrowDistance);
            }
            if (ThrowAngle != 0D)
            {
                hash ^= pbc::ProtobufEqualityComparers.BitwiseDoubleEqualityComparer.GetHashCode(ThrowAngle);
            }
            if (IsThrowDish != false)
            {
                hash ^= IsThrowDish.GetHashCode();
            }
            if (UseType != 0)
            {
                hash ^= UseType.GetHashCode();
            }
            if (SpeakText.Length != 0)
            {
                hash ^= SpeakText.GetHashCode();
            }
            if (Parameter1 != 0D)
            {
                hash ^= pbc::ProtobufEqualityComparers.BitwiseDoubleEqualityComparer.GetHashCode(Parameter1);
            }
            if (Parameter2 != 0D)
            {
                hash ^= pbc::ProtobufEqualityComparers.BitwiseDoubleEqualityComparer.GetHashCode(Parameter2);
            }
            if (IsSetTalent != false)
            {
                hash ^= IsSetTalent.GetHashCode();
            }
            if (Talent != 0)
            {
                hash ^= Talent.GetHashCode();
            }
            if (_unknownFields != null)
            {
                hash ^= _unknownFields.GetHashCode();
            }
            return(hash);
        }
        public static string ImageUrl(this Item item, ID imageFieldId, MediaUrlOptions options)
        {
            var imageField = (ImageField)item?.Fields?[imageFieldId];

            return(imageField?.MediaItem == null ? string.Empty : imageField.ImageUrl(options));
        }
Example #60
0
        public string GenerateQuery()
        {
            var query = $@" 
IF(NOT EXISTS(SELECT TOP (1) 1 from [dbo].[GenericAnnouncements] where ExternalId={ID.Safe()} ))
BEGIN
    INSERT INTO [dbo].[GenericAnnouncements]
               ([Id]
               ,[ExternalId]
               ,[HostSite]
               ,[Title]
               ,[Description]
               ,[Owner]
               ,[Images]
               ,[ThumbImages]
               ,[SmallImages]
               ,[LargeUrls]
               ,[Price]
               ,[First_Publication_Date]
               ,[Expiration_Date]
               ,[Category_Id]
               ,[Category_Name]
               ,[LinkUrl]
               ,[Extra]
               ,[LinkText]
               ,[City]
               ,[Latitude]
               ,[Langitude]
               ,[Region]
               ,[SourceType])
         VALUES
               (NEWID()
               ,{ID.Safe()}
               ,{HostSite.Safe()}
               ,{Title.Safe()}
               ,{Description.Safe()}
               ,{Owner.Safe()}
               ,{Images.Safe()}
               ,{ThumbImages.Safe()}
               ,{SmallImages.Safe()}
               ,{LargeUrls.Safe()}
               ,{Price.Safe()}
               ,{first_publication_date.Safe()}
               ,{expiration_date.Safe()}
               ,{category_id.Safe()}
               ,{category_name.Safe()}
               ,{LinkUrl.Safe()}
               ,{Extra.Safe()}
               ,{LinkText.Safe()}
               ,{City.Safe()}
               ,{Latitude.Safe()}
               ,{Langitude.Safe()}
               ,{Region.Safe()}
               ,0)
END;
ELSE
BEGIN
    UPDATE [dbo].[GenericAnnouncements]
       SET 
           [HostSite] = {HostSite.Safe()}
          ,[Title] = {Title.Safe()}
          ,[Description] = {Description.Safe()}
          ,[Owner] = {Owner.Safe()}
          ,[Images] = {Images.Safe()}
          ,[ThumbImages] = {ThumbImages.Safe()}
          ,[SmallImages] = {SmallImages.Safe()}
          ,[LargeUrls] = {LargeUrls.Safe()}
          ,[Price] = {Price.Safe()}
          ,[First_Publication_Date] = {first_publication_date.Safe()}
          ,[Expiration_Date] = {expiration_date.Safe()}
          ,[Category_Id] = {category_id.Safe()}
          ,[Category_Name] = {category_name.Safe()}
          ,[LinkUrl] = {LinkUrl.Safe()}
          ,[Extra] = {Extra.Safe()}
          ,[LinkText] = {LinkText.Safe()}
          ,[City] = {City.Safe()}
          ,[Latitude] = {Latitude.Safe()}
          ,[Langitude] = {Langitude.Safe()}
          ,[Region] = {Region.Safe()}
          --,[SourceType] = <SourceType, int,>
     WHERE ExternalId={ID.Safe()}

END;
";


            return(query);
        }