Esempio n. 1
0
        private static void init()
        {
            cp = new CompilerParameters();
            var options = new System.Collections.Generic.Dictionary<string, string>();
            options.Add("CompilerVersion", "v3.5");

            //adds all standard .net 3.5 namespaces
            cp.ReferencedAssemblies.Add("System.Core.dll");
            cp.ReferencedAssemblies.Add("System.dll");
            cp.ReferencedAssemblies.Add("mscorlib.dll");
            cp.ReferencedAssemblies.Add("System.Xml.dll");    
            cp.ReferencedAssemblies.Add("System.Data.dll");
            cp.ReferencedAssemblies.Add("System.Web.dll");
            cp.ReferencedAssemblies.Add("System.Drawing.dll");
            cp.ReferencedAssemblies.Add("System.Windows.Forms.dll");
            cp.ReferencedAssemblies.Add("System.ServiceModel.dll");
            cp.ReferencedAssemblies.Add("System.Workflow.ComponentModel.dll");
            cp.ReferencedAssemblies.Add("System.Workflow.Runtime.dll");
            cp.ReferencedAssemblies.Add("System.Workflow.Activities.dll");
            cp.ReferencedAssemblies.Add("WindowsBase.dll");
            cp.ReferencedAssemblies.Add("PresentationCore.dll");
            cp.ReferencedAssemblies.Add("PresentationFramework.dll");
            cp.CompilerOptions += " /unsafe ";


            compiler = new CSharpCodeProvider(options);
        }
Esempio n. 2
0
            public void Trigger( string category, string action )
            {
                // make sure this category exists. It must be added by the constructor of the derived event.
                Category categoryObj = Categories.Find( c => c.Name == category );
                if ( categoryObj == null )
                {
                    throw new Exception( string.Format( "Unknown Category {0} triggered for Event {1}", category, Name ) );
                }

                // if the action hasn't been performed yet, or we can perform it more than once, fire the analytic
                if ( categoryObj.PerformedActions.Contains( action ) == false || categoryObj.OncePerRun == false )
                {
                    // add it, which will fail if it's alread in the list
                    categoryObj.PerformedActions.Add( action );

                    if ( GeneralConfig.Use_Analytics == true )
                    {
#if !DEBUG
                        #if __IOS__
                            Foundation.NSDictionary nsAttribs = Foundation.NSDictionary.FromObjectAndKey( new Foundation.NSString( action ), new Foundation.NSString( categoryObj.Name ) );
                            LocalyticsBinding.Localytics.TagEvent( Name, nsAttribs );
                        #elif __ANDROID__
                            System.Collections.Generic.Dictionary<string, string> attribs = new System.Collections.Generic.Dictionary<string, string>();
                            attribs.Add( categoryObj.Name, action );
                            Com.Localytics.Android.Localytics.TagEvent( Name, attribs );
                        #endif
#endif
                    }
                }
            }
 public static System.Collections.Generic.List<SurveyNote> GetExcursionNotes(int excursionId)
 {
     DataSet ds = DatabaseOperationProvider.QueryProcedure("up_guest_getExcursionSurveyNotes", "note,items", new
     {
         excursion = excursionId
     });
     System.Collections.Generic.List<SurveyNote> result = (
         from DataRow row in ds.Tables["note"].Rows
         select SurveyProvider.factory.SurveyNote(row)).ToList<SurveyNote>();
     System.Collections.Generic.Dictionary<int, SurveyNote> notesDictionary = new System.Collections.Generic.Dictionary<int, SurveyNote>();
     result.ForEach(delegate (SurveyNote m)
     {
         notesDictionary.Add(m.Invitation, m);
     });
     SurveyNote cache = null;
     foreach (DataRow noteRow in ds.Tables["items"].Rows.Cast<DataRow>())
     {
         int invitation = noteRow.ReadInt("invitation");
         if (cache == null || cache.Invitation != invitation)
         {
             cache = notesDictionary[invitation];
         }
         cache.Notes.Add(new SurveyNoteItem
         {
             Category = noteRow.ReadNullableTrimmedString("id"),
             Note = noteRow.ReadNullableTrimmedString("note")
         });
     }
     return result;
 }
Esempio n. 4
0
        public static string HandleType(string name)
        {
            if (name == "Bridge.Int")
            {
                //it is hack, need to find good solution
                return "Number";
            }

            if (decodeRegex == null)
            {
                replacements = new System.Collections.Generic.Dictionary<string, string>(4);
                replacements.Add("\\(", "<");
                replacements.Add("\\)", ">");
                replacements.Add("Bridge.Int", "Number");

                decodeRegex = new Regex("(" + String.Join("|", replacements.Keys.ToArray()) + ")", RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.Multiline);
            }

            return decodeRegex.Replace
                (
                    name,
                    delegate(Match m) {
                        return replacements.ContainsKey(m.Value) ? replacements[m.Value] : replacements["\\" + m.Value];
                    }
                );
        }
		//Rolls back index to a chosen ID
		private void  RollBackLast(int id)
		{
			
			// System.out.println("Attempting to rollback to "+id);
			System.String ids = "-" + id;
			IndexCommit last = null;
			IList<IndexCommit> commits = IndexReader.ListCommits(dir);
			for (System.Collections.IEnumerator iterator = commits.GetEnumerator(); iterator.MoveNext(); )
			{
				IndexCommit commit = (IndexCommit) iterator.Current;
                System.Collections.Generic.IDictionary<string, string> ud = commit.GetUserData();
				if (ud.Count > 0)
					if (((System.String) ud["index"]).EndsWith(ids))
						last = commit;
			}
			
			if (last == null)
				throw new System.SystemException("Couldn't find commit point " + id);
			
			IndexWriter w = new IndexWriter(dir, new WhitespaceAnalyzer(), new RollbackDeletionPolicy(this, id), MaxFieldLength.UNLIMITED, last);
            System.Collections.Generic.IDictionary<string, string> data = new System.Collections.Generic.Dictionary<string, string>();
			data["index"] = "Rolled back to 1-" + id;
			w.Commit(data);
			w.Close();
		}
Esempio n. 6
0
		internal Result(System.Collections.IDictionary items)
			: base(items)
		{
			AdapterTypeMap = new System.Collections.Generic.Dictionary<Type, Type>();
			Track = new System.Collections.Specialized.StringCollection();
			MarkupTextWriter = typeof (System.Web.UI.HtmlTextWriter);
		}
 /// <summary>Returns an array of user-specific information for use by the application itself.</summary>
 /// <param name="uids">List of user IDs. This is a comma-separated list of user IDs.</param>
 /// <param name="fields">List of desired fields in return. This is a comma-separated list of field strings and is limited to these entries only: <code>uid</code>, <code>first_name</code>, <code>last_name</code>, <code>name</code>, <code>timezone</code>, <code>birthday</code>, <code>sex</code>, <code>affiliations</code> (regional type only), <code>locale</code>, <code>profile_url</code>, <code>proxied_email</code>.</param>
 public FacebookResponse<FacebookList<User>> GetStandardInfo(String[] uids, String[] fields) {
     System.Collections.Generic.Dictionary<string, object> args = new System.Collections.Generic.Dictionary<string, object>();
     args.Add("uids", uids);
     args.Add("fields", fields);
     var response = this.ExecuteRequest<FacebookList<User>>("Users.getStandardInfo", args);
     return response;
 }
 /// <summary>Returns metadata about all of the photo albums uploaded by the specified user.</summary>
 /// <param name="uid">Return albums created by this user. You must specify either <code>uid</code> or <code>aids</code>. The <code>uid</code> parameter has no default value.</param>
 /// <param name="aids">Return albums with aids in this list. This is a comma-separated list of aids. You must specify either <code>uid</code> or <code>aids</code>. The <code>aids</code> parameter has no default value.</param>
 public FacebookResponse<FacebookList<Album>> GetAlbums(Int64 uid, String[] aids) {
     System.Collections.Generic.Dictionary<string, object> args = new System.Collections.Generic.Dictionary<string, object>();
     args.Add("uid", uid);
     args.Add("aids", aids);
     var response = this.ExecuteRequest<FacebookList<Album>>("Photos.getAlbums", args);
     return response;
 }
 /// <summary>Creates and returns a new album owned by the current session user.</summary>
 /// <param name="name">The album name.</param>
 /// <param name="description">The album description.</param>
 public FacebookResponse<Album> CreateAlbum(String name, String description) {
     System.Collections.Generic.Dictionary<string, object> args = new System.Collections.Generic.Dictionary<string, object>();
     args.Add("name", name);
     args.Add("description", description);
     var response = this.ExecuteRequest<Album>("Photos.createAlbum", args);
     return response;
 }
 /// <summary>Returns the current allocation limit for your application for the specified integration point.</summary>
 /// <param name="user">The <a href="/index.php/User_ID" title="User ID">user ID</a> for the specific user whose allocations you want to to check. Specifying a user ID is relevant only with respect to the emails_per_day integration point for users who granted the email permission prior to the 2008 profile design update, per the note on <a href="/index.php/Notifications.sendEmail" title="Notifications.sendEmail">notifications.sendEmail</a>.</param>
 /// <param name="integrationPointName">The name of the integration point. Integration points include <code>notifications_per_day</code>, <code>announcement_notifications_per_week</code>, <code>requests_per_day</code>, <code>emails_per_day</code>, and <code>email_disable_message_location</code>.</param>
 public FacebookResponse<Int64> GetAllocation(Int64 user, String integrationPointName) {
     System.Collections.Generic.Dictionary<string, object> args = new System.Collections.Generic.Dictionary<string, object>();
     args.Add("user", user);
     args.Add("integration_point_name", integrationPointName);
     var response = this.ExecuteRequest<Int64>("Admin.getAllocation", args);
     return response;
 }
 /// <summary>Returns all visible groups according to the filters specified.</summary>
 /// <param name="uid">Filter by groups associated with a user with this UID.</param>
 /// <param name="gids">Filter by this list of group IDs. This is a comma-separated list of GIDs.</param>
 public FacebookResponse<FacebookList<Group>> Get(Int64 uid, String gids) {
     System.Collections.Generic.Dictionary<string, object> args = new System.Collections.Generic.Dictionary<string, object>();
     args.Add("uid", uid);
     args.Add("gids", gids);
     var response = this.ExecuteRequest<FacebookList<Group>>("Groups.get", args);
     return response;
 }
Esempio n. 12
0
        public static string GetPlaneNameByPlaneID(int planeid)
        {
            if (dictPlane == null)
            {

                SecureDBEntities1 db=new SecureDBEntities1();
                dictPlane = new Dictionary<int, tblERPlane>();
                var q= from n in db.tblERPlane  select n;
                foreach (tblERPlane planedata in q)
                {
                    try
                    {
                        dictPlane.Add(planedata.PlaneID, planedata);
                    }
                    catch (Exception ex)
                    {
                        ;
                    }
                }
      

            }

            return  dictPlane[planeid].PlaneName;

        }
 public System.Collections.Generic.List<DataFeed> GetDataFeed(PricingLibrary.FinancialProducts.IOption option, System.DateTime fromDate)
 {
     System.Collections.Generic.List<DataFeed> result = new System.Collections.Generic.List<DataFeed>() ;
     using (DataBaseDataContext mtdc = new DataBaseDataContext())
     {
         var result1 = (from s in mtdc.HistoricalShareValues where ((option.UnderlyingShareIds.Contains(s.id)) && (s.date >= fromDate)&&(s.date<=option.Maturity)) select s).OrderByDescending(d => d.date).ToList();
         System.DateTime curentdate = result1[result1.Count() - 1].date;
         System.Collections.Generic.Dictionary<String, decimal> priceList = new System.Collections.Generic.Dictionary<String, decimal>();
         for (int i = result1.Count() - 1; i >= 0 ; i--)
         {
             if (result1[i].date==curentdate)
             {
                 priceList.Add(result1[i].id.Trim(), result1[i].value);
             }
             else
             {
                 DataFeed datafeed = new DataFeed(curentdate, priceList);
                 result.Add(datafeed);
                 curentdate = result1[i].date;
                 priceList = new System.Collections.Generic.Dictionary<String, decimal>();
                 priceList.Add(result1[i].id.Trim(), result1[i].value);
             }
             if (i == 0)
             {
                 DataFeed datafeedOut = new DataFeed(curentdate, priceList);
                 result.Add(datafeedOut);
             }
         }
         return result;
     }
 }
Esempio n. 14
0
        public void ShowDialog(string customerID, IWin32Window parent, IBindingListView blist)
        {
            // Put the customer id in the window title.
            this.Text = "Orders for Customer ID: " + customerID;

            dataGridView1.AutoGenerateColumns = false;
            dataGridView1.DataSource = blist;

            // The check box column will be virtual.
            dataGridView1.VirtualMode = true;
            dataGridView1.Columns.Insert(0, new DataGridViewCheckBoxColumn());

            // Don't allow the column to be resizable.
            dataGridView1.Columns[0].Resizable = DataGridViewTriState.False;

            // Make the check box column frozen so it is always visible.
            dataGridView1.Columns[0].Frozen = true;

            // Put an extra border to make the frozen column more visible
            dataGridView1.Columns[0].DividerWidth = 1;

            // Make all columns except the first read only.
            foreach (DataGridViewColumn c in dataGridView1.Columns)
                if (c.Index != 0) c.ReadOnly = true;

            // Initialize the dictionary that contains the boolean check state.
            checkState = new Dictionary<int, bool>();

            // Show the dialog.
            this.ShowDialog(parent);
        }
 /// <summary>Associates a given "handle" with FBML markup so that the handle can be used within the <a href="/index.php/Fb:ref" title="Fb:ref">fb:ref</a> FBML tag.</summary>
 /// <param name="handle">The handle to associate with the given <a href="/index.php/FBML" title="FBML">FBML</a>.</param>
 /// <param name="fbml">The FBML to associate with the given handle.</param>
 public FacebookResponse<Boolean> SetRefHandle(String handle, String fbml) {
     System.Collections.Generic.Dictionary<string, object> args = new System.Collections.Generic.Dictionary<string, object>();
     args.Add("handle", handle);
     args.Add("fbml", fbml);
     var response = this.ExecuteRequest<Boolean>("Fbml.setRefHandle", args);
     return response;
 }
 /// <summary>Removes a specific <a href="/index.php/Extended_permission" title="Extended permission">extended permission</a> that a user explicitly granted to your application.</summary>
 /// <param name="uid">The <a href="/index.php/User_ID" title="User ID">user ID</a> of the user whose <a href="/index.php/Extended_permissions" title="Extended permissions">extended permission</a> you want to revoke. If you don't specify this parameter, then you must have a valid session for the current user, and that session's user will have the specified permission revoked.</param>
 /// <param name="perm">The <a href="/index.php/Extended_permissions" title="Extended permissions">extended permission</a> to revoke.</param>
 public FacebookResponse<Boolean> RevokeExtendedPermission(Int64 uid, String perm) {
     System.Collections.Generic.Dictionary<string, object> args = new System.Collections.Generic.Dictionary<string, object>();
     args.Add("uid", uid);
     args.Add("perm", perm);
     var response = this.ExecuteRequest<Boolean>("Auth.revokeExtendedPermission", args);
     return response;
 }
 /// <summary>Returns all cookies for a given user and application.</summary>
 /// <param name="name">The name of the cookie. If not specified, all the cookies for the given user get returned.</param>
 /// <param name="uid">The user from whom to get the cookies.</param>
 public FacebookResponse<FacebookList<Cookie>> GetCookies(String name, Int64 uid) {
     System.Collections.Generic.Dictionary<string, object> args = new System.Collections.Generic.Dictionary<string, object>();
     args.Add("name", name);
     args.Add("uid", uid);
     var response = this.ExecuteRequest<FacebookList<Cookie>>("Data.getCookies", args);
     return response;
 }
Esempio n. 18
0
 public int solution(string S)
 {
     // write your code in C# 6.0 with .NET 4.5 (Mono)
     string currentLine = string.Empty;
     int longestCall = 0;
     System.Collections.Generic.Dictionary<int, int> costs = new System.Collections.Generic.Dictionary<int, int>();
     int totalCost = 0;
     string[] timesAndPhones = S.Split(',', '\n');
     for (int index = 0; index < (timesAndPhones.Length / 2); index++)
     {
         int currentCost = 0;
         string[] timeComponents = timesAndPhones[index * 2].Split(':');
         int seconds = System.Convert.ToInt32(timeComponents[0]) * 3600 +
             System.Convert.ToInt32(timeComponents[1]) * 60 +
             System.Convert.ToInt32(timeComponents[2]);
         if (seconds < 5 * 60)
             currentCost = seconds * 3;
         else if (seconds == (5 * 60))
             currentCost = 5 * 150;
         else
             currentCost = ((seconds % 5) + 5) * 150;
         totalCost += currentCost;
         // save cost
         costs.Add(seconds, currentCost);
         // set longest call
         if (longestCall < seconds)
             longestCall = seconds;
     }
     return totalCost - costs[longestCall];
 }
Esempio n. 19
0
		void Start ()
		{
			Time.timeScale = 1.0f;

			//Create a Dictionary to contain all our Objects/Transforms
			System.Collections.Generic.Dictionary<string,Transform> colliders = new System.Collections.Generic.Dictionary<string,Transform> ();
			//Create our GameObjects and add their Transform components to the Dictionary we created above
			colliders.Add ("Top", new GameObject ().transform);
			colliders.Add ("Bottom", new GameObject ().transform);
			colliders.Add ("Right", new GameObject ().transform);
			colliders.Add ("Left", new GameObject ().transform);
			//Generate world space point information for position and scale calculations
			Vector3 cameraPos = Camera.main.transform.position;
			screenSize.x = Vector2.Distance (Camera.main.ScreenToWorldPoint (new Vector2 (0, 0)), Camera.main.ScreenToWorldPoint (new Vector2 (Screen.width, 0))) * 0.5f; //Grab the world-space position values of the start and end positions of the screen, then calculate the distance between them and store it as half, since we only need half that value for distance away from the camera to the edge
			screenSize.y = Vector2.Distance (Camera.main.ScreenToWorldPoint (new Vector2 (0, 0)), Camera.main.ScreenToWorldPoint (new Vector2 (0, Screen.height))) * 0.5f;
			//For each Transform/Object in our Dictionary
			foreach (KeyValuePair<string,Transform> valPair in colliders) {
					valPair.Value.gameObject.AddComponent<BoxCollider2D> (); //Add our colliders. Remove the "2D", if you would like 3D colliders.
					valPair.Value.name = valPair.Key + "Collider"; //Set the object's name to it's "Key" name, and take on "Collider".  i.e: TopCollider
					valPair.Value.parent = transform; //Make the object a child of whatever object this script is on (preferably the camera)
	
					if (valPair.Key == "Left" || valPair.Key == "Right") //Scale the object to the width and height of the screen, using the world-space values calculated earlier
							valPair.Value.localScale = new Vector3 (colThickness, screenSize.y * 2, colThickness);
					else
							valPair.Value.localScale = new Vector3 (screenSize.x * 2, colThickness, colThickness);
			}  
			//Change positions to align perfectly with outter-edge of screen, adding the world-space values of the screen we generated earlier, and adding/subtracting them with the current camera position, as well as add/subtracting half out objects size so it's not just half way off-screen
			colliders ["Right"].position = new Vector3 (cameraPos.x + screenSize.x + (colliders ["Right"].localScale.x * 0.5f), cameraPos.y, zPosition);
			colliders ["Left"].position = new Vector3 (cameraPos.x - screenSize.x - (colliders ["Left"].localScale.x * 0.5f), cameraPos.y, zPosition);
			colliders ["Top"].position = new Vector3 (cameraPos.x, cameraPos.y + screenSize.y + (colliders ["Top"].localScale.y * 0.5f), zPosition);
			colliders ["Bottom"].position = new Vector3 (cameraPos.x, cameraPos.y - screenSize.y - (colliders ["Bottom"].localScale.y * 0.5f), zPosition);
		}
Esempio n. 20
0
 /// <summary>Returns the session key bound to an auth_token, as returned by <a href="/index.php/Auth.createToken" title="Auth.createToken">auth.createToken</a> or in the callback URL.</summary>
 /// <param name="authToken">The token returned by <a href="/index.php/Auth.createToken" title="Auth.createToken">auth.createToken</a> and passed into login.php</param>
 public FacebookResponse<SessionInfo> GetSession(String authToken) {
     System.Collections.Generic.Dictionary<string, object> args = new System.Collections.Generic.Dictionary<string, object>();
     args.Add("auth_token", authToken);
     var response = this.ExecuteRequest<SessionInfo>("Auth.getSession", args);
     if (!response.IsError) this.FacebookContext.InitSession(response.Value);
     return response;
 }
Esempio n. 21
0
        public Model(string imageDetailsFileName)
        {
            XDocument doc = XDocument.Load ("/Application/" + imageDetailsFileName +".xml");

            var lines = from sprite in doc.Root.Elements (imageDetailsFileName)
                select new
                {
                    Name = sprite.Attribute("n").Value,
                    Position = sprite.Attribute ("position").Value,
                    Normal = sprite.Attribute("normal").Value,
                    Indices = sprite.Attribute("indices").Value,
                    ModelMatrix = sprite.Attribute("modelMatrix").Value,
                    MaterialIndex = sprite.Attribute("materialIndex").Value,
                    Count = (int)sprite.Attribute("count")
                };

            _positions = new Dictionary<string, string[]>();
            _normals = new Dictionary<string, string[]>();
            _indices = new Dictionary<string, string[]>();
            _modelMatrix = new Dictionary<string, string[]>();
            _materialIndex = new Dictionary<string, string>();

            foreach(var curLine in lines)
            {
                count = curLine.Count;
                _positions.Add (curLine.Name, curLine.Position.Split(','));
                _normals.Add (curLine.Name, curLine.Normal.Split(','));
                _indices.Add (curLine.Name, curLine.Indices.Split(','));
                _modelMatrix.Add (curLine.Name, curLine.ModelMatrix.Split(','));
                _materialIndex.Add (curLine.Name, curLine.MaterialIndex);
            }
        }
Esempio n. 22
0
        static public IEnumerator SendPostRequest(string url, byte[] data, Dictionary<string, string> headers, System.Action<WWW> callback, System.Action<string> errorCallback)
        {
            System.Collections.Generic.Dictionary<string, string> defaultHeaders = new System.Collections.Generic.Dictionary<string, string>(); ;
            if (data != null)
            {
                defaultHeaders.Add("Content-Type", "application/octet-stream");
                defaultHeaders.Add("Content-Length", data.Length.ToString());
            }

            if (headers != null)
            {
                foreach(KeyValuePair<string, string> pair in headers)
                {
                    defaultHeaders.Add(pair.Key, pair.Value);
                }                
            }

            WWW www = new WWW(url, data, defaultHeaders);
            yield return www;

            if (!System.String.IsNullOrEmpty(www.error))
            {
                if (errorCallback != null)
                {
                    errorCallback(www.error);
                }
            }
            else
            {
                callback(www);
            }
        }
		/// <summary>
		/// 
		/// </summary>
		/// <param name="uid"></param>
		/// <returns></returns>
		public FacebookResponse<String> IncrementCount(string uid)
		{
            System.Collections.Generic.Dictionary<string, object> args = new System.Collections.Generic.Dictionary<string, object>();
            args.Add("uid", uid);
			var response = this.ExecuteRequest<String>("Dashboard.incrementCount", args);
            return response;
        }
 /// <summary>Lets a user delete a Facebook note that was written through your application.</summary>
 /// <param name="title">The title of the note.</param>
 /// <param name="content">The note's content.</param>
 public FacebookResponse<Boolean> Delete(String title, String content) {
     System.Collections.Generic.Dictionary<string, object> args = new System.Collections.Generic.Dictionary<string, object>();
     args.Add("title", title);
     args.Add("content", content);
     var response = this.ExecuteRequest<Boolean>("Notes.delete", args);
     return response;
 }
Esempio n. 25
0
    public static void btnIniciar_onclick(string mail)
    {
        //sacar pass
        Dictionary<string, object> parameters = new System.Collections.Generic.Dictionary<string, object>();
        parameters.Add("@mail", mail);
        string pass = DataAccess.executeStoreProcedureString("spr_GET_Pass", parameters);
        if (!String.IsNullOrEmpty(pass))
        {
            try
            {
                var pv = new Dictionary<string, string>();
                var files = new Dictionary<string, Stream>();

                Common.SendMailByDictionary(pv, files, /*mail*/"*****@*****.**", "MandarPass", pass);
                HttpContext.Current.Session["passEnviadoBien"] = "true";
            }
            catch (Exception ex)
            {
                HttpContext.Current.Session["passEnviadoBien"] = "false";
            }
        }
        else
        {
            HttpContext.Current.Session["passEnviadoBien"] = "noEncontrado";
        }
    }
 /// <summary>Sets the FBML for a user's profile, including the content for both the profile box and the profile actions.</summary>
 /// <param name="profile">The FBML intended for the application profile box that appears on the Boxes tab on the user's profile.</param>
 /// <param name="profileMain">The FBML intended for the <a href="/index.php/New_Design_Narrow_Boxes" title="New Design Narrow Boxes">narrow profile box</a> on the Wall and Info tabs of the user's profile. <b>Note:</b> This attribute applies only to the new profile design that launched July 2008.</param>
 public FacebookResponse<Boolean> SetFBML(String profile, String profileMain) {
     System.Collections.Generic.Dictionary<string, object> args = new System.Collections.Generic.Dictionary<string, object>();
     args.Add("profile", profile);
     args.Add("profile_main", profileMain);
     var response = this.ExecuteRequest<Boolean>("Profile.setFBML", args);
     return response;
 }
 /// <summary>Sets the FBML for a user's profile, including the content for both the profile box and the profile actions.</summary>
 /// <param name="uid">The <a href="/index.php/User_ID" title="User ID">user ID</a> for the user whose profile you are updating, or the page ID in case of a Page. If this parameter is not specified, then it defaults to the session user.  <br/><b>Note:</b> This parameter applies only to Web applications and is required by them only if the <code>session_key</code> is not specified. Facebook returns an error if this parameter is passed by a desktop application.</param>
 public FacebookResponse<Boolean> SetFBML(Int64 uid) {
     if ((this.FacebookContext.ApplicationType & ApplicationType.Website)!= ApplicationType.Website)throw new InvalidOperationException("This overload cannot be called in this context");
     System.Collections.Generic.Dictionary<string, object> args = new System.Collections.Generic.Dictionary<string, object>();
     args.Add("uid", uid);
     var response = this.ExecuteRequest<Boolean>("Profile.setFBML", args);
     return response;
 }
Esempio n. 28
0
        public TheTVDB(FileInfo loadFrom, FileInfo cacheFile, CommandLineArgs args)
        {
            Args = args;

            System.Diagnostics.Debug.Assert(cacheFile != null);
            this.CacheFile = cacheFile;

            this.LastError = "";
            // this.WhoHasLock = new List<String>();
            this.Connected = false;
            this.ExtraEpisodes = new System.Collections.Generic.List<ExtraEp>();

            this.LanguageList = new System.Collections.Generic.Dictionary<string, string>();
            this.LanguageList["en"] = "English";

            this.XMLMirror = "http://thetvdb.com";
            this.BannerMirror = "http://thetvdb.com";
            this.ZIPMirror = "http://thetvdb.com";

            this.Series = new System.Collections.Generic.Dictionary<int, SeriesInfo>();
            this.New_Srv_Time = this.Srv_Time = 0;

            this.LoadOK = (loadFrom == null) || this.LoadCache(loadFrom);

            this.ForceReloadOn = new System.Collections.Generic.List<int>();
        }
 /// <summary>Returns all visible events according to the filters specified.</summary>
 /// <param name="uid">Filter by events associated with a user with this <code>uid</code>.</param>
 /// <param name="rsvpStatus">Filter by this RSVP status. The RSVP status should be one of the following strings:
 ///<ul><li> attending
 ///</li><li> unsure
 ///</li><li> declined
 ///</li><li> not_replied</param>
 public FacebookResponse<FacebookList<Event>> Get(Int64 uid, String rsvpStatus) {
     System.Collections.Generic.Dictionary<string, object> args = new System.Collections.Generic.Dictionary<string, object>();
     args.Add("uid", uid);
     args.Add("rsvp_status", rsvpStatus);
     var response = this.ExecuteRequest<FacebookList<Event>>("Events.get", args);
     return response;
 }
 public override System.Collections.Generic.IDictionary<string, object> AsDictionary()
 {
     System.Collections.Generic.Dictionary<string, object> result = new System.Collections.Generic.Dictionary<string, object>();
     result["PowerLines"] = this.PowerLines;
     result["CurrentPower"] = this.CurrentPower;
     return result;
 }
Esempio n. 31
0
 public override void OnAuthenticated(IServiceBase authService, IAuthSession session, IOAuthTokens tokens, System.Collections.Generic.Dictionary <string, string> authInfo)
 {
     if (session.UserName == AuthTests.UserNameWithSessionRedirect)
     {
         session.ReferrerUrl = AuthTests.SessionRedirectUrl;
     }
 }
Esempio n. 32
0
        protected void btnSelOrdersFinish_Click(object sender, System.EventArgs e)
        {
            bool   flag = false;
            string text = "";

            if (!string.IsNullOrEmpty(base.Request["CheckBoxGroup"]))
            {
                text = base.Request["CheckBoxGroup"];
            }
            if (text.Length <= 0)
            {
                this.ShowMsg("请先选择要批量确认收货的订单", false);
                return;
            }
            string[] array = text.Trim(new char[]
            {
                ','
            }).Split(new char[]
            {
                ','
            });
            int num  = 0;
            int num2 = 0;

            string[] array2 = array;
            for (int i = 0; i < array2.Length; i++)
            {
                string text2 = array2[i];
                if (!string.IsNullOrEmpty(text2))
                {
                    OrderInfo orderInfo = OrderHelper.GetOrderInfo(text2);
                    if (orderInfo != null)
                    {
                        System.Collections.Generic.Dictionary <string, LineItemInfo> lineItems = orderInfo.LineItems;
                        LineItemInfo lineItemInfo = new LineItemInfo();
                        foreach (System.Collections.Generic.KeyValuePair <string, LineItemInfo> current in lineItems)
                        {
                            lineItemInfo = current.Value;
                            if (lineItemInfo.OrderItemsStatus == OrderStatus.ApplyForRefund || lineItemInfo.OrderItemsStatus == OrderStatus.ApplyForReturns)
                            {
                                flag = true;
                                break;
                            }
                        }
                        if (!flag)
                        {
                            if (OrderHelper.ConfirmOrderFinish(orderInfo))
                            {
                                num++;
                                this.myNotifier.updateAction = UpdateAction.OrderUpdate;
                                this.myNotifier.actionDesc   = "订单已完成";
                                if (orderInfo.PayDate.HasValue)
                                {
                                    this.myNotifier.RecDateUpdate = orderInfo.PayDate.Value;
                                }
                                else
                                {
                                    this.myNotifier.RecDateUpdate = System.DateTime.Today;
                                }
                                this.myNotifier.DataUpdated += new StatisticNotifier.DataUpdatedEventHandler(this.myEvent.Update);
                                this.myNotifier.UpdateDB();
                            }
                        }
                        else
                        {
                            num2++;
                        }
                    }
                }
                flag = false;
            }
            if (num > 0)
            {
                string text3 = "批量确认收货了" + num.ToString() + "个订单";
                if (num2 > 0)
                {
                    text3 = text3 + "," + num2.ToString() + "个订单中有退货(款)未完成";
                }
                this.ShowMsg(text3, true);
            }
            else
            {
                this.ShowMsg("订单中商品有退货(款)不允许完成!", false);
            }
            this.BindOrders();
        }
Esempio n. 33
0
    protected void btn_Guardar_Click(object sender, EventArgs e)
    {
        if (txtEdo.Text.Trim().Equals("") || txtEdo_EN.Text.Trim().Equals(""))
        {
            popUpMessageControl1.setAndShowInfoMessage("El estado de envío es requerido.", Comun.MESSAGE_TYPE.Error);
        }
        else
        {
            Dictionary <string, object> parameters = new System.Collections.Generic.Dictionary <string, object>();
            parameters.Add("@Estado", txtEdo.Text);
            parameters.Add("@Estado_EN", txtEdo_EN.Text);

            parameters.Add("@UsuarioModifico", Session["idUsuario"]);
            if (Activo.Checked)
            {
                parameters.Add("@Activo", 1);
            }
            else
            {
                parameters.Add("@Activo", 0);
            }


            if (Accion.Value == "Añadir")
            {
                //Verificar que el valor "Razón" a insertar no estan anteriormente agregados
                Dictionary <string, object> find = new System.Collections.Generic.Dictionary <string, object>();
                find.Add("@Estado", txtEdo.Text);
                find.Add("@Estado_EN", txtEdo_EN.Text);
                find.Add("@UsuarioModifico", Session["idUsuario"]);

                if (dataaccess.executeStoreProcedureGetInt("spr_ExisteEdoEnvioPlantula", find) > 0)
                {
                    popUpMessageControl1.setAndShowInfoMessage("No se efectuarán cambios debido a que el estado ya existe.", Comun.MESSAGE_TYPE.Info);
                }
                else
                {
                    String Rs = dataaccess.executeStoreProcedureString("spr_EdoEnvioInsertar", parameters);
                    if (Rs.Equals("Repetido"))
                    {
                        popUpMessageControl1.setAndShowInfoMessage("Ese registro ya había sido capturado.", Comun.MESSAGE_TYPE.Error);
                    }
                    else
                    {
                        popUpMessageControl1.setAndShowInfoMessage("El Estado  \"" + txtEdo.Text + "\" se guardó exitosamente.", Comun.MESSAGE_TYPE.Success);
                    }
                }
            }
            else
            {
                if (Session["IdModuloCookie"] == null || Session["IdModuloCookie"].ToString() == "")
                {
                    popUpMessageControl1.setAndShowInfoMessage("Error #RGRL02: Se perdió la información del ID actual", Comun.MESSAGE_TYPE.Error);
                }
                else
                {
                    parameters.Add("@idEstado", Session["IdModuloCookie"].ToString());
                    String Rs = dataaccess.executeStoreProcedureString("spr_UpdateEdoEnvioPlantula", parameters);
                    if (Rs.Equals("Igual"))
                    {
                        popUpMessageControl1.setAndShowInfoMessage("No existieron cambios en la razón.", Comun.MESSAGE_TYPE.Info);
                    }
                    else
                    {
                        popUpMessageControl1.setAndShowInfoMessage("El  Estado de envío por plántula fue modificada.", Comun.MESSAGE_TYPE.Success);
                    }
                }
            }
            //obtieneModulo();

            //gv_Merma.DataSource = da.executeStoreProcedureDataTable("spr_MermaObtener", new Dictionary<string, object>());
            obtieneEdo();
            //VolverAlPanelInicial();
        }
        Accion.Value     = "Añadir";
        txtEdo.Text      = "";
        txtEdo_EN.Text   = "";
        btnCancelar.Text = GetLocalResourceObject("Limpiar").ToString();
        btn_Enviar.Text  = GetLocalResourceObject("Guardar").ToString();
    }
Esempio n. 34
0
        public static void XtractData(string filename, string tfilename)
        {
            char splc = ':';

            System.Console.WriteLine("Read DSV6 file: " + filename);
            var v = new Veranstaltung();

            string[] bs  = BlockFile(filename); //Dateinhalte einlesen und vorbereiten
            int      i   = 0;
            var      WKL = new System.Collections.Generic.Dictionary <string, Wettkampf>();

            do
            {
                if (bs[i].Trim().StartsWith("PFLICHTZEIT:"))
                {
                    var       xwknr = bs[i].Split(splc)[1].Trim();
                    Wettkampf xwk;
                    WKL.TryGetValue(xwknr, out xwk);
                    var    pz = bs[i + 5].Trim();
                    string cls;
                    if (bs[i + 4] == bs[i + 3])
                    {
                        cls = bs[i + 3];
                    }
                    else
                    {
                        cls = bs[i + 3] + "-" + bs[i + 4];
                    }

                    if (bs[i + 3] == "0" || bs[i + 3] == "")
                    {
                        cls = "-" + bs[i + 4];
                        cls = "offen";
                    }
                    if (bs[i + 4] == "9999" || bs[i + 4] == "")
                    {
                        cls = bs[i + 3] + "-";
                        cls = "offen";
                    }
                    if ((bs[i + 3] == "0" || bs[i + 3] == "") && (bs[i + 4] == "9999" || bs[i + 4] == ""))
                    {
                        cls = "offen";
                    }
                    var key = cls;
                    xwk.AddPZ(key, pz);
                }
                if (bs[i].Trim().StartsWith("ABSCHNITT:"))
                {
                    var absnr   = int.Parse(bs[i].Split(splc)[1]);
                    var absdate = DateTime.Parse(bs[i + 1]);
                    var abs     = new Abschnitt(absnr, absdate);
                    v.AddAbschnitt(abs);
                }
                if (bs[i].Trim().StartsWith("WETTKAMPF:"))
                {
                    var xwknr     = bs[i].Split(splc)[1].Trim();
                    var xabsnr    = int.Parse(bs[i + 2]);
                    var xwkkey    = bs[i + 4] + "m " + bs[i + 5];
                    var factorStr = bs[i + 3].Trim();
                    if (factorStr != "1" && factorStr != "")
                    {
                        xwkkey = factorStr + " x " + xwkkey;
                    }
                    //System.Console.WriteLine(xwknr.ToString() + " " + xabsnr.ToString() + " " + xwkkey);
                    var wk = new Wettkampf(xwknr, xwkkey, bs[i + 7], bs[i + 1]);
                    WKL.Add(xwknr, wk);
                    v.AddWettkampf(xabsnr, wk);
                }
                i += 1;
                //System.Console.WriteLine(bs[i-1]);
                //System.Console.WriteLine(bs[i]);
            } while (i < bs.Length && bs[i] != "DATEIENDE");
            System.Console.WriteLine("Write CSV file: " + tfilename);
            v.printOverview(tfilename);
        }
Esempio n. 35
0
        protected void Page_Load(object sender, System.EventArgs e)
        {
            int.TryParse(base.Request.QueryString["productId"], out this.productId);
            System.Data.DataSet   taobaoProductDetails = ProductHelper.GetTaobaoProductDetails(this.productId);
            System.Data.DataTable dataTable            = taobaoProductDetails.Tables[0];
            System.Collections.Generic.SortedDictionary <string, string> sortedDictionary = new System.Collections.Generic.SortedDictionary <string, string>();
            sortedDictionary.Add("SiteUrl", Hidistro.Membership.Context.HiContext.Current.SiteUrl);
            sortedDictionary.Add("_input_charset", "utf-8");
            sortedDictionary.Add("return_url", Globals.FullPath(Globals.GetSiteUrls().UrlData.FormatUrl("MakeTaobaoProductData_url")));
            sortedDictionary.Add("ProductId", this.productId.ToString());
            sortedDictionary.Add("HasSKU", dataTable.Rows[0]["HasSKU"].ToString());
            sortedDictionary.Add("ProductName", (string)dataTable.Rows[0]["ProductName"]);
            sortedDictionary.Add("ProductCode", (string)dataTable.Rows[0]["ProductCode"]);
            sortedDictionary.Add("CategoryName", (dataTable.Rows[0]["CategoryName"] == System.DBNull.Value) ? "" : ((string)dataTable.Rows[0]["CategoryName"]));
            sortedDictionary.Add("ProductLineName", (dataTable.Rows[0]["ProductLineName"] == System.DBNull.Value) ? "" : ((string)dataTable.Rows[0]["ProductLineName"]));
            sortedDictionary.Add("BrandName", (dataTable.Rows[0]["BrandName"] == System.DBNull.Value) ? "" : ((string)dataTable.Rows[0]["BrandName"]));
            sortedDictionary.Add("SalePrice", System.Convert.ToDecimal(dataTable.Rows[0]["SalePrice"]).ToString("F2"));
            sortedDictionary.Add("MarketPrice", (dataTable.Rows[0]["MarketPrice"] == System.DBNull.Value) ? "0" : System.Convert.ToDecimal(dataTable.Rows[0]["MarketPrice"]).ToString("F2"));
            sortedDictionary.Add("CostPrice", System.Convert.ToDecimal(dataTable.Rows[0]["CostPrice"]).ToString("F2"));
            sortedDictionary.Add("PurchasePrice", System.Convert.ToDecimal(dataTable.Rows[0]["PurchasePrice"]).ToString("F2"));
            sortedDictionary.Add("Stock", dataTable.Rows[0]["Stock"].ToString());
            System.Data.DataTable dataTable2 = taobaoProductDetails.Tables[1];
            if (dataTable2.Rows.Count > 0)
            {
                string text = string.Empty;
                foreach (System.Data.DataRow dataRow in dataTable2.Rows)
                {
                    object obj = text;
                    text = string.Concat(new object[]
                    {
                        obj,
                        dataRow["AttributeName"],
                        ":",
                        dataRow["ValueStr"],
                        ";"
                    });
                }
                text = text.Remove(text.Length - 1);
                sortedDictionary.Add("Attributes", text);
            }
            System.Data.DataTable dataTable3 = taobaoProductDetails.Tables[2];
            if (dataTable3.Rows.Count > 0)
            {
                System.Text.StringBuilder stringBuilder  = new System.Text.StringBuilder();
                System.Text.StringBuilder stringBuilder2 = new System.Text.StringBuilder();
                for (int i = dataTable3.Columns.Count - 1; i >= 0; i--)
                {
                    stringBuilder2.Append(dataTable3.Columns[i].ColumnName).Append(";");
                }
                foreach (System.Data.DataRow dataRow2 in dataTable3.Rows)
                {
                    for (int j = dataTable3.Columns.Count - 1; j >= 0; j--)
                    {
                        stringBuilder.Append(dataRow2[dataTable3.Columns[j].ColumnName]).Append(";");
                    }
                    stringBuilder.Remove(stringBuilder.Length - 1, 1).Append(",");
                }
                stringBuilder2.Remove(stringBuilder2.Length - 1, 1).Append(",").Append(stringBuilder.Remove(stringBuilder.Length - 1, 1));
                sortedDictionary.Add("skus", stringBuilder2.ToString());
            }
            System.Data.DataTable dataTable4 = taobaoProductDetails.Tables[3];
            if (dataTable4.Rows.Count > 0)
            {
                sortedDictionary.Add("Cid", dataTable4.Rows[0]["Cid"].ToString());
                if (dataTable4.Rows[0]["StuffStatus"] != System.DBNull.Value)
                {
                    sortedDictionary.Add("StuffStatus", (string)dataTable4.Rows[0]["StuffStatus"]);
                }
                sortedDictionary.Add("ProTitle", (string)dataTable4.Rows[0]["ProTitle"]);
                sortedDictionary.Add("Num", dataTable4.Rows[0]["Num"].ToString());
                sortedDictionary.Add("LocationState", (string)dataTable4.Rows[0]["LocationState"]);
                sortedDictionary.Add("LocationCity", (string)dataTable4.Rows[0]["LocationCity"]);
                sortedDictionary.Add("FreightPayer", (string)dataTable4.Rows[0]["FreightPayer"]);
                if (dataTable4.Rows[0]["PostFee"] != System.DBNull.Value)
                {
                    sortedDictionary.Add("PostFee", dataTable4.Rows[0]["PostFee"].ToString());
                }
                if (dataTable4.Rows[0]["ExpressFee"] != System.DBNull.Value)
                {
                    sortedDictionary.Add("ExpressFee", dataTable4.Rows[0]["ExpressFee"].ToString());
                }
                if (dataTable4.Rows[0]["EMSFee"] != System.DBNull.Value)
                {
                    sortedDictionary.Add("EMSFee", dataTable4.Rows[0]["EMSFee"].ToString());
                }
                sortedDictionary.Add("HasInvoice", dataTable4.Rows[0]["HasInvoice"].ToString());
                sortedDictionary.Add("HasWarranty", dataTable4.Rows[0]["HasWarranty"].ToString());
                sortedDictionary.Add("HasDiscount", dataTable4.Rows[0]["HasDiscount"].ToString());
                if (dataTable4.Rows[0]["PropertyAlias"] != System.DBNull.Value)
                {
                    sortedDictionary.Add("PropertyAlias", (string)dataTable4.Rows[0]["PropertyAlias"]);
                }
                if (dataTable4.Rows[0]["SkuProperties"] != System.DBNull.Value)
                {
                    sortedDictionary.Add("SkuProperties", (string)dataTable4.Rows[0]["SkuProperties"]);
                }
                if (dataTable4.Rows[0]["SkuQuantities"] != System.DBNull.Value)
                {
                    sortedDictionary.Add("SkuQuantities", (string)dataTable4.Rows[0]["SkuQuantities"]);
                }
                if (dataTable4.Rows[0]["SkuPrices"] != System.DBNull.Value)
                {
                    sortedDictionary.Add("SkuPrices", (string)dataTable4.Rows[0]["SkuPrices"]);
                }
                if (dataTable4.Rows[0]["SkuOuterIds"] != System.DBNull.Value)
                {
                    sortedDictionary.Add("SkuOuterIds", (string)dataTable4.Rows[0]["SkuOuterIds"]);
                }
                if (dataTable4.Rows[0]["inputpids"] != System.DBNull.Value)
                {
                    sortedDictionary.Add("inputpids", (string)dataTable4.Rows[0]["inputpids"]);
                }
                if (dataTable4.Rows[0]["inputstr"] != System.DBNull.Value)
                {
                    sortedDictionary.Add("inputstr", (string)dataTable4.Rows[0]["inputstr"]);
                }
                if (dataTable4.Rows[0]["FoodAttributes"] != System.DBNull.Value)
                {
                    sortedDictionary.Add("FoodAttributes", System.Web.HttpUtility.UrlEncode((string)dataTable4.Rows[0]["FoodAttributes"]));
                }
            }
            System.Collections.Generic.Dictionary <string, string> dictionary = OpenIdFunction.FilterPara(sortedDictionary);
            System.Text.StringBuilder stringBuilder3 = new System.Text.StringBuilder();
            foreach (System.Collections.Generic.KeyValuePair <string, string> current in dictionary)
            {
                stringBuilder3.Append(OpenIdFunction.CreateField(current.Key, current.Value));
            }
            sortedDictionary.Clear();
            dictionary.Clear();
            string action = "http://order1.kuaidiangtong.com/MakeTaoBaoData.aspx";

            if (dataTable4.Rows.Count > 0)
            {
                action = "http://order1.kuaidiangtong.com/UpdateTaoBaoData.aspx";
            }
            OpenIdFunction.Submit(OpenIdFunction.CreateForm(stringBuilder3.ToString(), action));
        }
Esempio n. 36
0
 /// <summary>
 /// Creates the control needed to filter (query) values using this field type.
 /// </summary>
 /// <param name="configurationValues">The configuration values.</param>
 /// <param name="id">The identifier.</param>
 /// <param name="required">if set to <c>true</c> [required].</param>
 /// <param name="filterMode">The filter mode.</param>
 /// <returns></returns>
 public override System.Web.UI.Control FilterControl(System.Collections.Generic.Dictionary <string, ConfigurationValue> configurationValues, string id, bool required, Rock.Reporting.FilterMode filterMode)
 {
     // This field type does not support filtering
     return(null);
 }
Esempio n. 37
0
        private System.Collections.Generic.Dictionary <string, SKUItem> GetSkus(ProductInfo product, decimal weight, System.Web.HttpContext context)
        {
            string text = context.Request.Form["SkuString"];

            System.Collections.Generic.Dictionary <string, SKUItem> dictionary;
            if (string.IsNullOrEmpty(text))
            {
                product.HasSKU = false;
                dictionary     = new System.Collections.Generic.Dictionary <string, SKUItem>
                {
                    {
                        "0",
                        new SKUItem
                        {
                            SkuId     = "0",
                            SKU       = product.ProductCode,
                            SalePrice = decimal.Parse(context.Request.Form["SalePrice"]),
                            CostPrice = 0m,
                            Stock     = int.Parse(context.Request.Form["Stock"]),
                            Weight    = weight
                        }
                    }
                };
            }
            else
            {
                product.HasSKU = true;
                dictionary     = new System.Collections.Generic.Dictionary <string, SKUItem>();
                text           = System.Web.HttpUtility.UrlDecode(text);
                string[] array = text.Split(new char[]
                {
                    '|'
                });
                for (int i = 0; i < array.Length; i++)
                {
                    string   text2  = array[i];
                    string[] array2 = text2.Split(new char[]
                    {
                        ','
                    });
                    SKUItem sKUItem = new SKUItem();
                    sKUItem.SKU       = array2[0].Replace("_", "-");
                    sKUItem.Weight    = weight;
                    sKUItem.Stock     = int.Parse(array2[1]);
                    sKUItem.SalePrice = decimal.Parse(array2[2]);
                    string   text3  = array2[3];
                    string   text4  = "";
                    string[] array3 = text3.Split(new char[]
                    {
                        ';'
                    });
                    for (int j = 0; j < array3.Length; j++)
                    {
                        string   text5  = array3[j];
                        string[] array4 = text5.Split(new char[]
                        {
                            ':'
                        });
                        int specificationId      = ProductTypeHelper.GetSpecificationId(product.TypeId.Value, array4[0]);
                        int specificationValueId = ProductTypeHelper.GetSpecificationValueId(specificationId, array4[1].Replace("\\", "/"));
                        text4 = text4 + specificationValueId + "_";
                        sKUItem.SkuItems.Add(specificationId, specificationValueId);
                    }
                    sKUItem.SkuId = text4.Substring(0, text4.Length - 1);
                    dictionary.Add(sKUItem.SkuId, sKUItem);
                }
            }
            return(dictionary);
        }
Esempio n. 38
0
 /// <summary>
 /// Creates the control needed to filter (query) values using this field type.
 /// </summary>
 /// <param name="configurationValues">The configuration values.</param>
 /// <param name="id">The identifier.</param>
 /// <param name="required">if set to <c>true</c> [required].</param>
 /// <param name="filterMode">The filter mode.</param>
 /// <returns></returns>
 public override System.Web.UI.Control FilterControl(System.Collections.Generic.Dictionary <string, ConfigurationValue> configurationValues, string id, bool required, Rock.Reporting.FilterMode filterMode)
 {
     return(base.FilterControl(configurationValues, id, required, filterMode));
 }
Esempio n. 39
0
 public Dictionary(System.Collections.Generic.Dictionary <TKey, TValue> target)
 {
     this.target = target;
 }
Esempio n. 40
0
 public void UpdateListItem(ISiteSetting siteSetting, string webUrl, string listName, int listItemID, System.Collections.Generic.Dictionary <object, object> fields)
 {
     throw new Exception("Not implemented yet");
 }
Esempio n. 41
0
 public OverworldData()
 {
     actorsData = new System.Collections.Generic.Dictionary <int, ActorData>();
     cellsData  = new System.Collections.Generic.Dictionary <int, TerrainCellData>();
     itemsData  = new System.Collections.Generic.Dictionary <int, ItemData>();
 }
        // event handler for Button
        public void SaveButton_Click_Base(object sender, EventArgs args)
        {
            bool   shouldRedirect = true;
            string target         = null;

            if (target == null)
            {
                target = "";             // avoid warning on VS
            }
            try {
                // Enclose all database retrieval/update code within a Transaction boundary
                DbUtils.StartTransaction();


                if (!this.IsPageRefresh)
                {
                    this.SaveData();
                }

                this.CommitTransaction(sender);
                string field            = "";
                string formula          = "";
                string displayFieldName = "";
                string value            = "";
                if (value == null)
                {
                    value = "";           // added to remove warning from VS
                }
                string id = "";
                if (id == null)
                {
                    id = "";        //added to avoid warning in VS
                }
                // retrieve necessary URL parameters
                if (!String.IsNullOrEmpty(Page.Request["Target"]))
                {
                    target = (this.Page as BaseApplicationPage).GetDecryptedURLParameter("Target");
                }
                if (!String.IsNullOrEmpty(Page.Request["IndexField"]))
                {
                    field = (this.Page as BaseApplicationPage).GetDecryptedURLParameter("IndexField");
                }
                if (!String.IsNullOrEmpty(Page.Request["Formula"]))
                {
                    formula = (this.Page as BaseApplicationPage).GetDecryptedURLParameter("Formula");
                }
                if (!String.IsNullOrEmpty(Page.Request["DFKA"]))
                {
                    displayFieldName = (this.Page as BaseApplicationPage).GetDecryptedURLParameter("DFKA");
                }

                if (!string.IsNullOrEmpty(target) && !string.IsNullOrEmpty(field))
                {
                    if (this.TrapIdentifiersRecordControl != null && this.TrapIdentifiersRecordControl.DataSource != null)
                    {
                        id = this.TrapIdentifiersRecordControl.DataSource.GetValue(this.TrapIdentifiersRecordControl.DataSource.TableAccess.TableDefinition.ColumnList.GetByAnyName(field)).ToString();
                        if (!string.IsNullOrEmpty(formula))
                        {
                            System.Collections.Generic.IDictionary <String, Object> variables = new System.Collections.Generic.Dictionary <String, Object>();
                            variables.Add(this.TrapIdentifiersRecordControl.DataSource.TableAccess.TableDefinition.TableCodeName, this.TrapIdentifiersRecordControl.DataSource);
                            value = EvaluateFormula(formula, this.TrapIdentifiersRecordControl.DataSource, null, variables);
                        }
                        else if (displayFieldName == "")
                        {
                            value = id;
                        }
                        else
                        {
                            value = this.TrapIdentifiersRecordControl.DataSource.GetValue(this.TrapIdentifiersRecordControl.DataSource.TableAccess.TableDefinition.ColumnList.GetByAnyName(displayFieldName)).ToString();
                        }
                    }
                    if (value == null)
                    {
                        value = id;
                    }
                    BaseClasses.Utils.MiscUtils.RegisterAddButtonScript(this, target, id, value);
                    shouldRedirect = false;
                }
                else if (!string.IsNullOrEmpty(target))
                {
                    BaseClasses.Utils.MiscUtils.RegisterAddButtonScript(this, target, null, null);
                    shouldRedirect = false;
                }
            } catch (Exception ex) {
                // Upon error, rollback the transaction
                this.RollBackTransaction(sender);
                shouldRedirect   = false;
                this.ErrorOnPage = true;

                // Report the error message to the end user
                BaseClasses.Utils.MiscUtils.RegisterJScriptAlert(this, "BUTTON_CLICK_MESSAGE", ex.Message);
            } finally {
                DbUtils.EndTransaction();
            }
            if (shouldRedirect)
            {
                this.ShouldSaveControlsToSession = true;
                this.RedirectBack();
            }
        }
Esempio n. 43
0
        private void btnUpdate_Click(object sender, System.EventArgs e)
        {
            if (this.categoryId == 0)
            {
                this.categoryId = (int)this.ViewState["ProductCategoryId"];
            }
            if (this.categoryId == 0)
            {
                this.ShowMsg("请选择商品分类", false);
                return;
            }
            ProductInfo productInfo = new ProductInfo();

            productInfo.ProductId  = this.productId;
            productInfo.CategoryId = this.categoryId;
            CategoryInfo category = SubsiteCatalogHelper.GetCategory(productInfo.CategoryId);

            if (category != null)
            {
                productInfo.MainCategoryPath = category.Path + "|";
            }
            productInfo.ProductName      = this.txtProductName.Text;
            productInfo.ShortDescription = this.txtShortDescription.Text;
            productInfo.Description      = this.fckDescription.Text;
            productInfo.Title            = this.txtTitle.Text;
            productInfo.MetaDescription  = this.txtMetaDescription.Text;
            productInfo.MetaKeywords     = this.txtMetaKeywords.Text;
            if (!string.IsNullOrEmpty(this.txtMarketPrice.Text))
            {
                productInfo.MarketPrice = new decimal?(decimal.Parse(this.txtMarketPrice.Text));
            }
            System.Collections.Generic.Dictionary <string, decimal> skuSalePrice = null;
            if (!string.IsNullOrEmpty(this.txtSkuPrice.Text))
            {
                skuSalePrice = this.GetSkuPrices();
            }
            ProductSaleStatus productSaleStatus = ProductSaleStatus.OnStock;

            if (this.radInStock.Checked)
            {
                productSaleStatus = ProductSaleStatus.OnStock;
            }
            if (this.radUnSales.Checked)
            {
                productSaleStatus = ProductSaleStatus.UnSale;
            }
            if (this.radOnSales.Checked)
            {
                productSaleStatus = ProductSaleStatus.OnSale;
            }
            if (productSaleStatus == ProductSaleStatus.OnSale)
            {
                bool flag = false;
                System.Xml.XmlDocument xmlDocument = new System.Xml.XmlDocument();
                try
                {
                    xmlDocument.LoadXml(this.txtSkuPrice.Text);
                    System.Xml.XmlNodeList xmlNodeList = xmlDocument.SelectNodes("//item");
                    if (xmlNodeList != null && xmlNodeList.Count > 0)
                    {
                        foreach (System.Xml.XmlNode xmlNode in xmlNodeList)
                        {
                            decimal d = decimal.Parse(xmlNode.Attributes["price"].Value);
                            if (d < decimal.Parse(this.litLowestSalePrice.Text))
                            {
                                flag = true;
                                break;
                            }
                        }
                    }
                }
                catch
                {
                }
                if (flag)
                {
                    this.ShowMsg("此商品的一口价已经低于了最低零售价,不允许上架", false);
                    return;
                }
            }
            System.Collections.Generic.IList <int> list = new System.Collections.Generic.List <int>();
            if (!string.IsNullOrEmpty(this.txtProductTag.Text.Trim()))
            {
                string   text = this.txtProductTag.Text.Trim();
                string[] array;
                if (text.Contains(","))
                {
                    array = text.Split(new char[]
                    {
                        ','
                    });
                }
                else
                {
                    array = new string[]
                    {
                        text
                    };
                }
                string[] array2 = array;
                for (int i = 0; i < array2.Length; i++)
                {
                    string value = array2[i];
                    list.Add(System.Convert.ToInt32(value));
                }
            }
            productInfo.SaleStatus = productSaleStatus;
            int displaySequence = 0;

            int.TryParse(this.txtDisplaySequence.Text, out displaySequence);
            productInfo.DisplaySequence = displaySequence;
            if (SubSiteProducthelper.UpdateProduct(productInfo, skuSalePrice, list))
            {
                this.litralProductTag.SelectedValue = list;
                this.ShowMsg("修改商品成功", true);
            }
        }
Esempio n. 44
0
 public override void OnAuthenticated(IServiceBase authService, IAuthSession session, IAuthTokens tokens, System.Collections.Generic.Dictionary <string, string> authInfo)
 {
     "OnAuthenticated()".Print();
 }
Esempio n. 45
0
 public MapReduce.NET.Service.StatusMessage Start(string config, System.Collections.Generic.Dictionary <string, string> parameters)
 {
     return(base.Channel.Start(config, parameters));
 }
        private void HandleClientComm(object client)
        {
            TcpClient     tcpClient    = (TcpClient)client;
            NetworkStream clientStream = tcpClient.GetStream();
            string        id           = getId(clientStream);

            if (clientID != id)
            {
                sendPayload(clientStream, Payload.PAYLOAD_EXIT);
                tcpClient.Close();
                if (!clientNames.ContainsKey(id))
                {
                    clientNames.Add(id, getCurrentTime());
                }
                else
                {
                    clientNames[id] = getCurrentTime();
                }
                return;
            }
            connected = true;
            ConsoleColor current = Console.ForegroundColor;

            while (true)
            {
                try{
                    Console.Write(id + "> ");
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    System.Text.RegularExpressions.Regex myRegex = new System.Text.RegularExpressions.Regex("(?<cmd>^\"[^\"]*\"|\\S*) *(?<prm>.*)?");
                    System.Text.RegularExpressions.Match m       = myRegex.Match(Console.ReadLine());
                    Console.ForegroundColor = ConsoleColor.Green;
                    if (m.Success)
                    {
                        if (m.Groups[1].Value == "cd")
                        {
                            Console.WriteLine(System.Text.ASCIIEncoding.ASCII.GetString(sendPayload(clientStream, String.Format(Payload.PAYLOAD_CD, m.Groups[2].Value.Replace("\\", "\\\\")))));
                        }
                        else if (m.Groups[1].Value == "exit" || m.Groups[1].Value == "quit")
                        {
                            Console.WriteLine(System.Text.ASCIIEncoding.ASCII.GetString(sendPayload(clientStream, Payload.PAYLOAD_EXIT)));
                            Console.ForegroundColor = current;
                            break;
                        }
                        else if (m.Groups[1].Value == "upload")
                        {
                            System.Collections.Generic.Dictionary <string, string> parameters = getParameters(m.Groups[2].Value);
                            Console.WriteLine(System.Text.ASCIIEncoding.ASCII.GetString(sendPayload(clientStream, String.Format(Payload.PAYLOAD_UPLOAD, parameters["o"].Replace("\\", "\\\\"), Convert.ToBase64String(File.ReadAllBytes(parameters["i"]))))));
                        }
                        else if (m.Groups[1].Value == "download")
                        {
                            System.Collections.Generic.Dictionary <string, string> parameters = getParameters(m.Groups[2].Value);
                            File.WriteAllBytes(parameters["o"], sendPayload(clientStream, String.Format(Payload.PAYLOAD_DOWNLOAD, parameters["i"].Replace("\\", "\\\\"))));
                            Console.WriteLine("File " + parameters["i"] + " Downloaded to " + parameters["o"]);
                        }
                        else if (m.Groups[1].Value == "pwd")
                        {
                            Console.WriteLine(System.Text.ASCIIEncoding.ASCII.GetString(sendPayload(clientStream, Payload.PAYLOAD_PWD)));
                        }
                        else if (m.Groups[1].Value == "rm")
                        {
                            Console.WriteLine(System.Text.ASCIIEncoding.ASCII.GetString(sendPayload(clientStream, String.Format(Payload.PAYLOAD_DELETE, m.Groups[2].Value.Replace("\\", "\\\\")))));
                        }
                        else if (m.Groups[1].Value == "ls")
                        {
                            Console.ForegroundColor = ConsoleColor.Blue;
                            Console.WriteLine(System.Text.ASCIIEncoding.ASCII.GetString(sendPayload(clientStream, Payload.PAYLOAD_LIST_DIR)));
                            Console.ForegroundColor = ConsoleColor.Green;
                            Console.WriteLine(System.Text.ASCIIEncoding.ASCII.GetString(sendPayload(clientStream, Payload.PAYLOAD_LS)));
                        }
                        else if (m.Groups[1].Value == "terminate")
                        {
                            Console.WriteLine(System.Text.ASCIIEncoding.ASCII.GetString(sendPayload(clientStream, Payload.PAYLOAD_TERMINATE)));
                            Console.ForegroundColor = current;
                            break;
                        }
                        else if (m.Groups[1].Value == "persist")
                        {
                            System.Collections.Generic.Dictionary <string, string> parameters = getParameters(m.Groups[2].Value);
                            Console.WriteLine(System.Text.ASCIIEncoding.ASCII.GetString(sendPayload(clientStream, String.Format(Payload.PAYLOAD_PERSIST, parameters["n"]))));
                        }
                    }
                }catch (Exception exception) {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(exception);
                }
                Console.ForegroundColor = current;
            }
            tcpClient.Close();
            connected       = false;
            clientNames[id] = getCurrentTime();
            clientID        = NO_CLIENT_ID;
        }
    protected void viewer_ReportLoaded(object sender, EventArgs e)
    {
        bool renderName        = (Request.QueryString["RenderNames"] != null);
        int  systemParamsCount = renderName ? 2 : 1;

        if ((Request.QueryString[PXUrl.HideScriptParameter] != null))
        {
            systemParamsCount++;
        }
        if ((Request.QueryString[PXUrl.PopupParameter] != null))
        {
            systemParamsCount++;
        }
        if ((Request.QueryString[PXPageCache.TimeStamp] != null))
        {
            systemParamsCount++;
        }
        if ((Request.QueryString[PXUrl.UNum] != null))
        {
            systemParamsCount++;
        }
        if ((Request.QueryString[PXUrl.CompanyID] != null))
        {
            systemParamsCount++;
        }
        if ((Request.QueryString["_" + PXUrl.CompanyID] != null))
        {
            systemParamsCount++;
        }

        if (Request.QueryString[PX.Reports.Messages.Max] != null)
        {
            viewer.Report.TopCount = Convert.ToInt32(Request.QueryString[PX.Reports.Messages.Max].ToString());
        }

        object passed = sessionReportParams.Count > 0 ? sessionReportParams[0] : null;

        if (passed == null && PXSiteMap.IsPortal && this.Request.QueryString["PortalAccessAllowed"] == null)
        {
            throw new PXException(ErrorMessages.NotEnoughRights, viewer.Report.ReportName);
        }
        Dictionary <string, string> pars = passed as Dictionary <string, string>;

        if (pars == null && Request.QueryString.Count > systemParamsCount && !(Request.AppRelativeCurrentExecutionFilePath ?? "").StartsWith("~/rest/"))
        {
            foreach (string key in Request.QueryString.AllKeys)
            {
                if (String.Compare(key, "ID", StringComparison.OrdinalIgnoreCase) == 0 ||
                    String.Compare(key, "RenderNames", StringComparison.OrdinalIgnoreCase) == 0 ||
                    String.Compare(key, PXUrl.CompanyID, StringComparison.OrdinalIgnoreCase) == 0 ||
                    String.Compare(key, "_CompanyID", StringComparison.OrdinalIgnoreCase) == 0 || PXUrl.SystemParams.Contains(key))
                {
                    continue;
                }
                if (pars == null)
                {
                    pars = new System.Collections.Generic.Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);
                }
                pars[key] = Request.QueryString[key];
            }
        }

        viewer.Report.RenderNames = renderName;
        viewer.Report.Title       = this.Title;
        // reportid from params
        string reportIdParamValue = pars != null && pars.ContainsKey(ReportLauncherHelper._REPORTID_PARAM_KEY) ? pars[ReportLauncherHelper._REPORTID_PARAM_KEY] : string.Empty;

        if (string.IsNullOrEmpty(reportIdParamValue))
        {
            var id = Page.Request.Params["id"];
            reportIdParamValue = id != null?id.Replace(".rpx", string.Empty) : null;
        }
        // true if params are intended for the current report
        bool isCurrReportParams = passed == null ||
                                  String.Equals(_screenID, reportIdParamValue, StringComparison.OrdinalIgnoreCase);

        // clear params if they are not for the current report
        if (!isCurrReportParams && pars != null)
        {
            pars = null;
            PXContext.Session.PageInfo[VirtualPathUtility.ToAbsolute(this.Page.Request.Path)] = null;
        }

        if (!viewer.HideParameters)
        {
            viewer.Report.RequestParams = !(passed is IPXResultset) && (!isCurrReportParams || pars == null);
        }
        if (passed is IPXResultset && viewer.Report.RequestContext)
        {
            this.usrCaption.ScreenUrl = string.Empty;
        }

        if (isCurrReportParams)
        {
            for (int i = 0; i < sessionReportParams.Count; i++)
            {
                try
                {
                    if (i == 0)
                    {
                        ReportLauncherHelper.LoadParameters(viewer.Report, pars, (SoapNavigator)((PXReportViewer)sender).GetNavigator());
                        // Clear report data from session after report has been loaded when there is only one report
                        if (sessionReportParams.Count == 1 && (pars == null || pars.Count == 1 && pars.ContainsKey(ReportLauncherHelper._REPORTID_PARAM_KEY)))
                        {
                            PXContext.Session.PageInfo[VirtualPathUtility.ToAbsolute(this.Page.Request.Path)] = null;
                        }
                    }
                    else
                    {
                        ReportLauncherHelper.LoadParameters(viewer.Report.SiblingReports[i - 1], sessionReportParams[i], (SoapNavigator)((PXReportViewer)sender).GetNavigator());
                    }
                }
                catch
                {
                    PXContext.Session.PageInfo[VirtualPathUtility.ToAbsolute(this.Page.Request.Path)] = null;
                    throw;
                }
            }
        }
    }
 /// <summary>
 /// Creates the control(s) necessary for prompting user for a new value
 /// </summary>
 /// <param name="configurationValues">The configuration values.</param>
 /// <param name="id"></param>
 /// <returns>
 /// The control
 /// </returns>
 public override System.Web.UI.Control EditControl(System.Collections.Generic.Dictionary <string, ConfigurationValue> configurationValues, string id)
 {
     return(new RockTextBox {
         ID = id
     });
 }
Esempio n. 49
0
        private void InsertFeatures(object param)
        {
            DF3DApplication app = DF3DApplication.Application;

            if (app == null || app.Current3DMapControl == null)
            {
                return;
            }
            EditParameters editParameters = (EditParameters)param;

            if (editParameters == null)
            {
                return;
            }
            System.Collections.Generic.Dictionary <DF3DFeatureClass, IRowBufferCollection> geometryMap = editParameters.geometryMap;
            if (geometryMap != null)
            {
                CommandManagerServices.Instance().StartCommand();
                FDECommand fDECommand  = new FDECommand(true, true);
                int        nTotalCount = editParameters.nTotalCount;
                int        num         = 0;
                //System.IAsyncResult asyncResult = MainFrmService.ResultSetPanel.BeginInvoke(this._clearSelection);
                //MainFrmService.ResultSetPanel.EndInvoke(asyncResult);
                foreach (DF3DFeatureClass current in geometryMap.Keys)
                {
                    if (this._bgWorker.CancellationPending)
                    {
                        break;
                    }
                    IFeatureClass        featureClass         = current.GetFeatureClass();
                    IRowBufferCollection rowBufferCollection  = new RowBufferCollectionClass();
                    IRowBufferCollection rowBufferCollection2 = geometryMap[current];
                    int num2 = 0;
                    while (num2 < rowBufferCollection2.Count && !this._bgWorker.CancellationPending)
                    {
                        this._manualResult.WaitOne();
                        System.Threading.Thread.Sleep(1);
                        IRowBuffer value = rowBufferCollection2.Get(num2);
                        rowBufferCollection.Add(value);
                        num++;
                        string userState       = string.Format(StringParser.Parse("${res:feature_progress_finished}"), num, nTotalCount);
                        int    percentProgress = num * 100 / nTotalCount;
                        this._bgWorker.ReportProgress(percentProgress, userState);
                        num2++;
                    }
                    if (rowBufferCollection.Count > 0)
                    {
                        CommonUtils.Instance().FdeUndoRedoManager.InsertFeatures(featureClass, rowBufferCollection);
                        //object[] args = new object[]
                        //{
                        //    current,
                        //    rowBufferCollection2,
                        //    true,
                        //    false
                        //};
                        //asyncResult = MainFrmService.ResultSetPanel.BeginInvoke(this._InsertSelection, args);
                        //MainFrmService.ResultSetPanel.EndInvoke(asyncResult);
                        rowBufferCollection.Clear();
                    }
                }
                fDECommand.SetSelectionMap();
                CommandManagerServices.Instance().CallCommand(fDECommand);
                app.Workbench.UpdateMenu();
            }
        }
Esempio n. 50
0
        private IEnvelope ImportOsg(IFeatureClass fc, string filePath)
        {
            try
            {
                IEnvelope env = null;

                if (fc == null || !File.Exists(filePath))
                {
                    return(env);
                }

                string           modelName       = Path.GetFileNameWithoutExtension(filePath);
                IResourceManager resourceManager = fc.FeatureDataSet as IResourceManager;
                if (resourceManager == null)
                {
                    return(env);
                }
                if (!resourceManager.CheckResourceName(modelName))
                {
                    return(env);
                }
                IResourceFactory resourceFactory = new ResourceFactory();

                System.Collections.Generic.Dictionary <string, IEnvelope> modelInfos = this.GetModelInfos(resourceManager, modelName);
                fc.FeatureDataSet.DataSource.StartEditing();
                if (modelInfos.Keys.Contains(modelName))
                {
                    if (!sameNameDlg.IsApplicatonAll)//非应用于全部
                    {
                        string tipMessage = string.Format("{0}模型已经存在!", modelName);
                        sameNameDlg.TipMessage = tipMessage;
                        sameNameDlg.ShowDialog();
                    }
                    if (sameNameDlg.IsOverWriter)//如果覆盖就先删除
                    {
                        resourceManager.DeleteModel(modelName);
                        modelInfos.Remove(modelName);
                    }
                    else
                    {
                        env = modelInfos[modelName];
                    }
                }
                if (!modelInfos.Keys.Contains(modelName))
                {
                    Gvitech.CityMaker.Resource.IModel simplifiedModel = null;
                    Gvitech.CityMaker.Resource.IModel model           = null;
                    IMatrix      matrix = null;
                    IPropertySet propertySet;
                    resourceFactory.CreateModelAndImageFromFileEx(filePath, out propertySet, out simplifiedModel, out model, out matrix);
                    if (model == null || model.GroupCount == 0)
                    {
                        return(env);
                    }
                    if (!resourceManager.AddModel(modelName, model, simplifiedModel))
                    {
                        return(env);                                                             //向资源中添加
                    }
                    modelInfos[modelName] = model.Envelope;
                    env = modelInfos[modelName];

                    if (propertySet != null && propertySet.Count > 0)
                    {
                        //获得资源的图片
                        System.Collections.Generic.List <string> imageNames = GetImageNames(resourceManager);
                        string[] allKeys = propertySet.GetAllKeys();
                        string[] array   = allKeys;
                        for (int i = 0; i < array.Length; i++)
                        {
                            string text2 = array[i];
                            if (imageNames.Contains(text2))
                            {
                                if (!sameNameDlg.IsApplicatonAll)//非应用于全部
                                {
                                    string tipMessage2 = string.Format("{0}贴图已存在!", text2);
                                    sameNameDlg.TipMessage = tipMessage2;
                                    sameNameDlg.ShowDialog();
                                }
                                if (sameNameDlg.IsOverWriter)//是否覆盖
                                {
                                    resourceManager.DeleteImage(text2);
                                    imageNames.Remove(text2);
                                }
                            }

                            if (!imageNames.Contains(text2))
                            {
                                if (!resourceManager.CheckResourceName(text2))
                                {
                                }
                                else
                                {
                                    imageNames.Add(text2);
                                    Gvitech.CityMaker.Resource.IImage image = propertySet.GetProperty(text2) as Gvitech.CityMaker.Resource.IImage;
                                    resourceManager.AddImage(text2, image);
                                }
                            }
                        }
                    }
                }
                fc.FeatureDataSet.DataSource.StopEditing(true);
                return(env);
            }
            catch (Exception ex)
            {
                fc.FeatureDataSet.DataSource.StopEditing(false);
                return(null);
            }
        }
Esempio n. 51
0
        private void UpdateAttribute(object param)
        {
            DF3DApplication app = DF3DApplication.Application;

            if (app == null || app.Current3DMapControl == null)
            {
                return;
            }
            EditParameters editParameters = (EditParameters)param;

            if (editParameters == null)
            {
                return;
            }
            string           featureClassGuid = editParameters.featureClassGuid;
            DF3DFeatureClass featureClassInfo = DF3DFeatureClassManager.Instance.GetFeatureClassByID(featureClassGuid);

            if (featureClassInfo == null)
            {
                return;
            }
            CommandManagerServices.Instance().StartCommand();
            FDECommand cmd         = new FDECommand(false, true);
            int        nTotalCount = editParameters.nTotalCount;
            int        num         = 0;

            if (featureClassInfo.GetFeatureClass().HasTemporal() && CommonUtils.Instance().EnableTemproalEdit)
            {
                IConnectionInfo connectionInfo = new ConnectionInfoClass();
                connectionInfo.FromConnectionString(featureClassInfo.GetFeatureClass().DataSource.ConnectionInfo.ToConnectionString());
                IDataSource      dataSource      = ((IDataSourceFactory) new DataSourceFactoryClass()).OpenDataSource(connectionInfo);
                IFeatureDataSet  featureDataSet  = dataSource.OpenFeatureDataset(CommonUtils.Instance().GetCurrentFeatureDataset().Name);
                IFeatureClass    featureClass    = featureDataSet.OpenFeatureClass(featureClassInfo.GetFeatureClass().Name);
                ITemporalManager temporalManager = featureClass.TemporalManager;
                ITemporalCursor  temporalCursor  = temporalManager.Search(new TemporalFilterClass
                {
                    IdsFilter = editParameters.fidList
                });
                while (temporalCursor.MoveNext())
                {
                    this._manualResult.WaitOne();
                    num++;
                    string userState       = string.Format(StringParser.Parse("${res:feature_progress_finished}"), num, nTotalCount);
                    int    percentProgress = num * 100 / nTotalCount;
                    this._bgWorker.ReportProgress(percentProgress, userState);
                    bool       flag      = false;
                    int        currentId = temporalCursor.CurrentId;
                    IRowBuffer row       = featureClass.GetRow(currentId);
                    base.UpdateRowBuffer(ref row, editParameters.colName, editParameters.regexDataList);
                    ITemporalInstanceCursor temporalInstances = temporalCursor.GetTemporalInstances(false);
                    TemporalInstance        temporalInstance;
                    while ((temporalInstance = temporalInstances.NextInstance()) != null)
                    {
                        if (temporalInstance.StartDatetime == editParameters.TemproalTime)
                        {
                            flag = true;
                            temporalInstances.Update(row);
                            break;
                        }
                    }
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(temporalInstances);
                    if (!flag)
                    {
                        temporalCursor.Insert(editParameters.TemproalTime, row);
                    }
                }
                System.Runtime.InteropServices.Marshal.ReleaseComObject(temporalCursor);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(temporalManager);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(featureClass);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(featureDataSet);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(dataSource);
            }
            else
            {
                IFeatureClass featureClass2 = featureClassInfo.GetFeatureClass();
                System.Collections.Generic.Dictionary <int, string> dictionary = new System.Collections.Generic.Dictionary <int, string>();
                IRowBufferCollection rowBufferCollection  = new RowBufferCollectionClass();
                IRowBufferCollection rowBufferCollection2 = new RowBufferCollectionClass();
                for (int i = 0; i < editParameters.fidList.Length; i++)
                {
                    if (this._bgWorker.CancellationPending)
                    {
                        CommonUtils.Instance().FdeUndoRedoManager.UpdateFeatures(featureClass2, rowBufferCollection2);
                        break;
                    }
                    this._manualResult.WaitOne();
                    System.Threading.Thread.Sleep(1);
                    int        num2 = editParameters.fidList[i];
                    IRowBuffer row2 = featureClass2.GetRow(num2);
                    if (row2 != null)
                    {
                        string value = base.UpdateRowBuffer(ref row2, editParameters.colName, editParameters.regexDataList);
                        rowBufferCollection.Add(row2);
                        rowBufferCollection2.Add(row2);
                        dictionary[num2] = value;
                        num++;
                        string userState2       = string.Format(StringParser.Parse("${res:feature_progress_finished}"), num, nTotalCount);
                        int    percentProgress2 = num * 100 / nTotalCount;
                        this._bgWorker.ReportProgress(percentProgress2, userState2);
                    }
                }
                if (dictionary.Count > 0)
                {
                    CommonUtils.Instance().FdeUndoRedoManager.UpdateFeatures(featureClass2, rowBufferCollection2);
                    object[] args = new object[]
                    {
                        featureClassInfo,
                        editParameters.colName,
                        dictionary
                    };
                    //System.IAsyncResult asyncResult = MainFrmService.ResultSetPanel.BeginInvoke(this._updateSelection, args);
                    //MainFrmService.ResultSetPanel.EndInvoke(asyncResult);
                }
            }
            CommandManagerServices.Instance().CallCommand(cmd);
            app.Workbench.UpdateMenu();
        }
 public ValueCollection(System.Collections.Generic.Dictionary <TKey, TValue> dictionary)
 {
 }
Esempio n. 53
0
        public async Task <ActionResult> SignInCallback()
        {
            var sams_endpoint_authorization    = _configuration["sams:endpoint_authorization"];
            var sams_endpoint_token            = _configuration["sams:endpoint_token"];
            var sams_endpoint_user_info        = _configuration["sams:endpoint_user_info"];
            var sams_endpoint_token_validation = _configuration["sams:token_validation"];
            var sams_endpoint_user_info_sys    = _configuration["sams:endpoint_user_info_sys"];
            var sams_client_id     = _configuration["sams:client_id"];
            var sams_client_secret = _configuration["sams:client_secret"];

            var sams_callback_url = _configuration["sams:callback_url"];

            //?code=6c17b2a3-d65a-44fd-a28c-9aee982f80be&state=a4c8326ca5574999aa13ca02e9384c3d
            // Retrieve code and state from query string, pring for debugging
            var querystring       = Request.QueryString.Value;
            var querystring_skip  = querystring.Substring(1, querystring.Length - 1);
            var querystring_array = querystring_skip.Split("&");

            var querystring_dictionary = new Dictionary <string, string>();

            foreach (string item in querystring_array)
            {
                var pair = item.Split("=");
                querystring_dictionary.Add(pair[0], pair[1]);
            }

            var code  = querystring_dictionary["code"];
            var state = querystring_dictionary["state"];

            System.Diagnostics.Debug.WriteLine($"code: {code}");
            System.Diagnostics.Debug.WriteLine($"state: {state}");

            HttpClient client  = new HttpClient();
            var        request = new HttpRequestMessage(HttpMethod.Post, sams_endpoint_token);

            /*
             * request.Content = new FormUrlEncodedContent(new Dictionary<string, string> {
             *  { "client_id", sams_client_id },
             *  { "client_secret", sams_client_secret },
             *  { "grant_type", "client_credentials" },
             *  { "code", code },
             * });
             */

            request.Content = new FormUrlEncodedContent(new Dictionary <string, string> {
                { "client_id", sams_client_id },
                { "client_secret", sams_client_secret },
                { "grant_type", "authorization_code" },
                { "code", code },
                { "scope", "openid profile email" },
                { "redirect_uri", sams_callback_url }
            });


            var response = await client.SendAsync(request);

            response.EnsureSuccessStatusCode();

            var payload       = JObject.Parse(await response.Content.ReadAsStringAsync());
            var access_token  = payload.Value <string>("access_token");
            var refresh_token = payload.Value <string>("refresh_token");
            var expires_in    = payload.Value <int>("expires_in");


            var scope = payload.Value <string>("scope");

            //HttpContext.Session.SetString("access_token", access_token);
            //HttpContext.Session.SetString("refresh_token", refresh_token);

            var unix_time = DateTimeOffset.UtcNow.AddSeconds(expires_in);
            //HttpContext.Session.SetString("expires_at", unix_time.ToString());



            var id_token = payload.Value <string>("id_token");;
            var id_array = id_token.Split('.');


            var replaced_value = id_array[1].Replace('-', '+').Replace('_', '/');
            var base64         = replaced_value.PadRight(replaced_value.Length + (4 - replaced_value.Length % 4) % 4, '=');


            var id_0 = DecodeToken(id_array[0]);
            var id_1 = DecodeToken(id_array[1]);

            var id_body = Base64Decode(base64);

            var user_info_sys_request = new HttpRequestMessage(HttpMethod.Post, sams_endpoint_user_info + "?token=" + id_token);


            user_info_sys_request.Headers.Add("Authorization", "Bearer " + access_token);
            user_info_sys_request.Headers.Add("client_id", sams_client_id);
            user_info_sys_request.Headers.Add("client_secret", sams_client_secret);

            /*
             * user_info_sys_request.Content = new FormUrlEncodedContent(new Dictionary<string, string> {
             *  { "client_id", sams_client_id },
             *  { "client_secret", sams_client_secret },
             *  { "grant_type", "client_credentials" },
             *  { "scope", scope },
             * });
             */



            response = await client.SendAsync(user_info_sys_request);

            response.EnsureSuccessStatusCode();

            var temp_string = await response.Content.ReadAsStringAsync();

            payload = JObject.Parse(temp_string);


            var email = payload.Value <string>("email");


            //check if user exists
            var config_couchdb_url     = _configuration["mmria_settings:couchdb_url"];
            var config_timer_user_name = _configuration["mmria_settings:timer_user_name"];
            var config_timer_password  = _configuration["mmria_settings:timer_password"];

            mmria.common.model.couchdb.user user = null;
            try
            {
                string request_string     = config_couchdb_url + "/_users/" + System.Web.HttpUtility.HtmlEncode("org.couchdb.user:"******"GET", null, request_string, null, config_timer_user_name, config_timer_password);
                var    responseFromServer = await user_curl.executeAsync();

                user = Newtonsoft.Json.JsonConvert.DeserializeObject <mmria.common.model.couchdb.user>(responseFromServer);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

            mmria.common.model.couchdb.document_put_response user_save_result = null;

            if (user == null)// if user does NOT exists create user with email
            {
                user = add_new_user(email.ToLower(), Guid.NewGuid().ToString());

                try
                {
                    Newtonsoft.Json.JsonSerializerSettings settings = new Newtonsoft.Json.JsonSerializerSettings();
                    settings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
                    var object_string = Newtonsoft.Json.JsonConvert.SerializeObject(user, settings);

                    string user_db_url = config_couchdb_url + "/_users/" + user._id;

                    var user_curl          = new mmria.server.cURL("PUT", null, user_db_url, object_string, config_timer_user_name, config_timer_password);
                    var responseFromServer = await user_curl.executeAsync();

                    user_save_result = Newtonsoft.Json.JsonConvert.DeserializeObject <mmria.common.model.couchdb.document_put_response>(responseFromServer);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
            }

            //create login session
            if (user_save_result == null || user_save_result.ok)
            {
                var session_data = new System.Collections.Generic.Dictionary <string, string>(StringComparer.InvariantCultureIgnoreCase);
                session_data["access_token"]  = access_token;
                session_data["refresh_token"] = refresh_token;
                session_data["expires_at"]    = unix_time.ToString();

                await create_user_principal(user.name, new List <string>(), unix_time.DateTime);


                var Session_Event_Message = new mmria.server.model.actor.Session_Event_Message
                                            (
                    DateTime.Now,
                    user.name,
                    this.GetRequestIP(),
                    mmria.server.model.actor.Session_Event_Message.Session_Event_Message_Action_Enum.successful_login
                                            );

                _actorSystem.ActorOf(Props.Create <mmria.server.model.actor.Record_Session_Event>()).Tell(Session_Event_Message);



                var Session_Message = new mmria.server.model.actor.Session_Message
                                      (
                    Guid.NewGuid().ToString(), //_id =
                    null,                      //_rev =
                    DateTime.Now,              //date_created =
                    DateTime.Now,              //date_last_updated =
                    null,                      //date_expired =

                    true,                      //is_active =
                    user.name,                 //user_id =
                    this.GetRequestIP(),       //ip =
                    Session_Event_Message._id, // session_event_id =
                    session_data
                                      );

                _actorSystem.ActorOf(Props.Create <mmria.server.model.actor.Post_Session>()).Tell(Session_Message);
                Response.Cookies.Append("sid", Session_Message._id);
                Response.Cookies.Append("expires_at", unix_time.ToString());
                //return RedirectToAction("Index", "HOME");
                //return RedirectToAction("Index", "HOME");
            }

            return(RedirectToAction("Index", "HOME"));

            // Generate JWT for token request
            //var cert = new X509Certificate2(Server.MapPath("~/App_Data/cert.pfx"), "1234");

            /*
             * var cert = new X509Certificate2();
             * var signingCredentials = new SigningCredentials(new X509SecurityKey(cert), SecurityAlgorithms.RsaSha256);
             * var header = new JwtHeader(signingCredentials);
             *
             * var header = new JwtHeader();
             * var payload = new JwtPayload
             * {
             *  {"iss", sams_client_id},
             *  {"sub", sams_client_id},
             *  {"aud", $"{sams_endpoint_token}"},
             *  {"jti", Guid.NewGuid().ToString("N")},
             *  {"exp", (int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds + 5 * 60}
             * };
             * var securityToken = new JwtSecurityToken(header, payload);
             * var handler = new JwtSecurityTokenHandler();
             * var tokenString = handler.WriteToken(securityToken);
             *
             * // Send POST to make token request
             * using (var wb = new WebClient())
             * {
             *  var data = new NameValueCollection();
             *  data["client_assertion"] = tokenString;
             *  data["client_assertion_type"] = HttpUtility.HtmlEncode("urn:ietf:params:oauth:client-assertion-type:jwt-bearer");
             *  data["code"] = code;
             *  data["grant_type"] = "authorization_code";
             *
             *  //var response = wb.UploadValues($"{IdpUrl}/api/openid_connect/token", "POST", data);
             *  var response = wb.UploadValues($"{sams_endpoint_token}", "POST", data);
             *
             *  var responseString = Encoding.ASCII.GetString(response);
             *  dynamic tokenResponse = JObject.Parse(responseString);
             *
             *  var token = handler.ReadToken((String)tokenResponse.id_token) as JwtSecurityToken;
             *  var userId = token.Claims.First(c => c.Type == "sub").Value;
             *  var userEmail = token.Claims.First(c => c.Type == "email").Value;
             *
             *  TempData["id"] = userId;
             *  TempData["email"] = userEmail;
             *  //return RedirectToAction("Index", "HOME");
             *  return RedirectToAction("Index", "HOME");
             * }*/
        }
Esempio n. 54
0
 private void UpdateGeometry(object param)
 {
     try
     {
         DF3DApplication app = DF3DApplication.Application;
         if (app == null || app.Current3DMapControl == null)
         {
             return;
         }
         EditParameters editParameters = (EditParameters)param;
         if (editParameters != null)
         {
             System.Collections.Generic.Dictionary <DF3DFeatureClass, IRowBufferCollection> geometryMap = editParameters.geometryMap;
             if (geometryMap != null)
             {
                 CommandManagerServices.Instance().StartCommand();
                 FDECommand cmd         = new FDECommand(false, true);
                 int        nTotalCount = editParameters.nTotalCount;
                 int        num         = 0;
                 foreach (DF3DFeatureClass current in geometryMap.Keys)
                 {
                     if (this._bgWorker.CancellationPending)
                     {
                         break;
                     }
                     IRowBufferCollection rowBufferCollection = geometryMap[current];
                     if (current.GetFeatureClass().HasTemporal() && CommonUtils.Instance().EnableTemproalEdit)
                     {
                         IConnectionInfo connectionInfo = new ConnectionInfoClass();
                         connectionInfo.FromConnectionString(current.GetFeatureClass().DataSource.ConnectionInfo.ToConnectionString());
                         IDataSource     dataSource     = ((IDataSourceFactory) new DataSourceFactoryClass()).OpenDataSource(connectionInfo);
                         IFeatureDataSet featureDataSet = dataSource.OpenFeatureDataset(CommonUtils.Instance().GetCurrentFeatureDataset().Name);
                         IFeatureClass   featureClass   = featureDataSet.OpenFeatureClass(current.GetFeatureClass().Name);
                         int             position       = featureClass.GetFields().IndexOf(featureClass.FidFieldName);
                         System.Collections.Generic.Dictionary <int, IRowBuffer> dictionary = new System.Collections.Generic.Dictionary <int, IRowBuffer>();
                         for (int i = 0; i < rowBufferCollection.Count; i++)
                         {
                             IRowBuffer rowBuffer = rowBufferCollection.Get(i);
                             int        key       = (int)rowBuffer.GetValue(position);
                             dictionary[key] = rowBuffer;
                         }
                         ITemporalManager temporalManager = featureClass.TemporalManager;
                         ITemporalCursor  temporalCursor  = temporalManager.Search(new TemporalFilterClass
                         {
                             IdsFilter = dictionary.Keys.ToArray <int>()
                         });
                         while (temporalCursor.MoveNext() && !this._bgWorker.CancellationPending)
                         {
                             this._manualResult.WaitOne();
                             System.Threading.Thread.Sleep(1);
                             num++;
                             string userState       = string.Format(StringParser.Parse("${res:feature_progress_finished}"), num, nTotalCount);
                             int    percentProgress = num * 100 / nTotalCount;
                             this._bgWorker.ReportProgress(percentProgress, userState);
                             bool flag      = false;
                             int  currentId = temporalCursor.CurrentId;
                             ITemporalInstanceCursor temporalInstances = temporalCursor.GetTemporalInstances(false);
                             TemporalInstance        temporalInstance;
                             while ((temporalInstance = temporalInstances.NextInstance()) != null)
                             {
                                 if (temporalInstance.StartDatetime == editParameters.TemproalTime)
                                 {
                                     flag = true;
                                     temporalInstances.Update(dictionary[currentId]);
                                     break;
                                 }
                             }
                             System.Runtime.InteropServices.Marshal.ReleaseComObject(temporalInstances);
                             if (!flag)
                             {
                                 temporalCursor.Insert(editParameters.TemproalTime, dictionary[currentId]);
                             }
                         }
                         System.Runtime.InteropServices.Marshal.ReleaseComObject(temporalCursor);
                         System.Runtime.InteropServices.Marshal.ReleaseComObject(temporalManager);
                         System.Runtime.InteropServices.Marshal.ReleaseComObject(featureClass);
                         System.Runtime.InteropServices.Marshal.ReleaseComObject(featureDataSet);
                         System.Runtime.InteropServices.Marshal.ReleaseComObject(dataSource);
                     }
                     else
                     {
                         IFeatureClass featureClass2 = current.GetFeatureClass();
                         int           num2          = 0;
                         while (num2 < rowBufferCollection.Count && !this._bgWorker.CancellationPending)
                         {
                             this._manualResult.WaitOne();
                             System.Threading.Thread.Sleep(1);
                             num++;
                             string userState2       = string.Format(StringParser.Parse("${res:feature_progress_finished}"), num, nTotalCount);
                             int    percentProgress2 = num * 100 / nTotalCount;
                             this._bgWorker.ReportProgress(percentProgress2, userState2);
                             num2++;
                         }
                         CommonUtils.Instance().FdeUndoRedoManager.UpdateFeatures(featureClass2, rowBufferCollection);
                     }
                 }
                 CommandManagerServices.Instance().CallCommand(cmd);
                 app.Workbench.UpdateMenu();
             }
         }
     }
     catch (System.Runtime.InteropServices.COMException ex)
     {
         XtraMessageBox.Show(ex.Message);
     }
     catch (System.UnauthorizedAccessException)
     {
         XtraMessageBox.Show(StringParser.Parse("${res:Dataset_InsufficientPermission}"));
     }
     catch (System.Exception e)
     {
         LoggingService.Error(e.Message);
     }
 }
Esempio n. 55
0
 internal void ResetPageExpressions()
 {
     _PageExprReferences = null;                         // clear it out; not needed once page header/footer are processed
 }
Esempio n. 56
0
        static void Main(string[] args)
        {
            Dictionary <char, char> intvalues = new System.Collections.Generic.Dictionary <char, char>();

            intvalues.Add('1', '1');
            intvalues.Add('2', '2');
            intvalues.Add('3', '3');
            intvalues.Add('4', '4');
            intvalues.Add('5', '5');
            intvalues.Add('6', '6');
            intvalues.Add('7', '7');
            intvalues.Add('8', '8');
            intvalues.Add('9', '9');
            intvalues.Add('0', '0');
            // intvalues.Add('.', '.');

            Dictionary <string, string> SIGNOP = new System.Collections.Generic.Dictionary <string, string>();

            SIGNOP.Add("+=", "COMP_ASSGN");
            SIGNOP.Add("-=", "COMP_ASSGN");
            SIGNOP.Add("*=", "COMP_ASSGN");
            SIGNOP.Add("/=", "COMP_ASSGN");
            SIGNOP.Add("%=", "COMP_ASSGN");
            SIGNOP.Add("=", "=");

            Dictionary <string, string> PM = new System.Collections.Generic.Dictionary <string, string>();

            PM.Add("+", "PM");
            PM.Add("-", "PM");

            Dictionary <string, string> RO = new System.Collections.Generic.Dictionary <string, string>();

            RO.Add("<", "ROP");
            RO.Add(">", "ROP");
            RO.Add("<=", "ROP");
            RO.Add(">=", "ROP");
            RO.Add("!=", "ROP");
            RO.Add("==", "ROP");
            RO.Add("!", "!");



            Dictionary <string, string> MDM = new System.Collections.Generic.Dictionary <string, string>();

            MDM.Add("*", "MDM");
            MDM.Add("/", "MDM");
            MDM.Add("%", "MDM");

            Dictionary <string, string> LO = new System.Collections.Generic.Dictionary <string, string>();

            LO.Add("&&", "&&");
            LO.Add("||", "&&");
            Dictionary <string, string> INC = new System.Collections.Generic.Dictionary <string, string>();

            INC.Add("++", "INC_DEC");
            INC.Add("--", "INC_DEC");
            Dictionary <string, string> PUNCTUATORS = new System.Collections.Generic.Dictionary <string, string>();


            PUNCTUATORS.Add("{", "{");
            PUNCTUATORS.Add("}", "}");
            PUNCTUATORS.Add(")", ")");
            PUNCTUATORS.Add("(", "(");
            PUNCTUATORS.Add(";", ";");
            PUNCTUATORS.Add(".", ".");
            PUNCTUATORS.Add("[", "[");
            PUNCTUATORS.Add("]", "]");
            PUNCTUATORS.Add(",", ",");
            PUNCTUATORS.Add(":", ":");

            Dictionary <string, string> PUNCTUATOR = new System.Collections.Generic.Dictionary <string, string>();


            PUNCTUATOR.Add("{", "{");
            PUNCTUATOR.Add("}", "}");
            PUNCTUATOR.Add(")", ")");
            PUNCTUATOR.Add("(", "(");
            PUNCTUATOR.Add(";", ";");
            PUNCTUATOR.Add("[", "[");
            PUNCTUATOR.Add("]", "]");
            PUNCTUATOR.Add(",", ",");
            PUNCTUATOR.Add(":", ":");



            Dictionary <string, string> KEYWORDS = new Dictionary <string, string>();

            KEYWORDS.Add("for", "for");


            Dictionary <string, string> Foreach = new Dictionary <string, string>();

            KEYWORDS.Add("foreach", "foreach");
            Dictionary <string, string> WHILE = new Dictionary <string, string>();

            KEYWORDS.Add("while", "while");
            KEYWORDS.Add("do", "do");


            Dictionary <string, string> Then = new Dictionary <string, string>();

            KEYWORDS.Add("then", "then");

            Dictionary <string, string> If = new Dictionary <string, string>();

            KEYWORDS.Add("if", "if");
            Dictionary <string, string> Else = new Dictionary <string, string>();

            KEYWORDS.Add("else", "else");
            Dictionary <string, string> Elseif = new Dictionary <string, string>();

            KEYWORDS.Add("else_if", "else_if");



            Dictionary <string, string> Switch = new Dictionary <string, string>();

            KEYWORDS.Add("switch", "switch");
            Dictionary <string, string> Case = new Dictionary <string, string>();

            KEYWORDS.Add("case", "case");
            Dictionary <string, string> List = new Dictionary <string, string>();

            KEYWORDS.Add("List", "List");
            Dictionary <string, string> Class = new Dictionary <string, string>();

            KEYWORDS.Add("class", "class");
            KEYWORDS.Add("Main", "Main");
            KEYWORDS.Add("Public", "ACC_MOD");
            KEYWORDS.Add("Private", "ACC_MOD");
            KEYWORDS.Add("void", "void");


            Dictionary <string, string> Abstract = new Dictionary <string, string>();

            KEYWORDS.Add("abs", "ABSTRACT");
            Dictionary <string, string> Inheritance = new Dictionary <string, string>();

            KEYWORDS.Add("extend", "INHERITANCE");

            Dictionary <string, string> Interface = new Dictionary <string, string>();

            KEYWORDS.Add("iextend", "INTERFACE");

            Dictionary <string, string> Override = new Dictionary <string, string>();

            KEYWORDS.Add("override", "override");
            Dictionary <string, string> Try = new Dictionary <string, string>();

            KEYWORDS.Add("try", "try");
            Dictionary <string, string> Catch = new Dictionary <string, string>();

            KEYWORDS.Add("catch", "catch");
            KEYWORDS.Add("finally", "finally");
            KEYWORDS.Add("default", "default");
            KEYWORDS.Add("break", "break");
            KEYWORDS.Add("return", "return");



            Dictionary <string, string> New = new Dictionary <string, string>();

            KEYWORDS.Add("new", "new");
            //  Dictionary<string, string> KEWORDS = new Dictionary<string, string>();
            KEYWORDS.Add("int", "DT");
            KEYWORDS.Add("float", "DT");
            KEYWORDS.Add("char", "DT");
            KEYWORDS.Add("string", "DT");
            KEYWORDS.Add("boolean", "DT");

            Dictionary <char, char> DOT = new Dictionary <char, char>();

            DOT.Add('.', '.');
            Dictionary <string, string> BOOLEANCONST = new Dictionary <string, string>();

            KEYWORDS.Add("true", "BOOLEAN_CONST");
            KEYWORDS.Add("false", "BOOLEAN_CONST");



            var  temp = "";
            char c    = ' ';
            //string enter = "\r\n";



            var file = new StreamWriter("C:\\Users\\ADMIN\\Desktop\\tokenset.txt");  // File.Create("C:\\Users\\ADMIN\\Desktop\\tokenset.txt");



            string s = File.ReadAllText("1.txt");

            int e    = 0;
            int line = 1;

            int i = 0;

            for (; i < s.Length; i++)
            {
                temp = "";

                if (s[i] == '\r' || e == 1)
                {
                    e    = 0;
                    temp = "";
                    ++line;

                    i = i + 2;
                }


                int allow = 0;

                int dotCounter = 0;


                ///////String/////////////

                if (s.Length <= i)
                {
                    break;
                }
                if (s[i] == ' ')
                {
                    temp = "";
                    ++i;
                    if (s.Length <= i)
                    {
                        break;
                    }
                }
                if (s[i] == '"')
                {
                    i++;
                    while (s[i] != '"')
                    {
                        if (s[i] == '\\')
                        {
                            ++i;
                            if (s.Length <= i)
                            {
                                allow = 1;
                                temp  = temp + s[--i];
                                // Console.WriteLine("({0},{1},{2})", "Laxical Error", "_", line);
                                break;
                            }
                            else

                            if (s[i] == '\r')
                            {
                                temp  = temp + s[--i];
                                allow = 1;

                                //   Console.WriteLine("({0},{1},{2})", "Laxical Error", "_", line);
                                e = 1;

                                break;
                            }
                            else
                            if (s[i] == ' ')
                            {
                                temp = temp + s[--i];

                                allow = 1;
                                break;
                            }
                            else
                            {
                                temp = temp + s[i];
                            }
                        }
                        else
                        {
                            if (s[i] == '\r')
                            {
                                allow = 1;

                                e = 1;
                                // Console.WriteLine("({0},{1},{2})", "Laxical Error", "_", line);
                                --i;
                                break;
                            }

                            temp = temp + s[i];
                        }



                        i++;
                        if (s.Length == i)
                        {
                            allow = 1;
                            break;
                        }
                    }


                    if (allow == 0)
                    {
                        Console.WriteLine("{0} {1} {2}", "STRING_CONST", temp, line);
                        file.WriteLine("{0} {1} {2}", "STRING_CONST", temp, line);
                    }
                    if (allow == 1)
                    {
                        Console.WriteLine("{0} {1} {2}", "Invalid", temp, line);
                        file.WriteLine("{0} {1} {2}", "Invalid", temp, line);
                    }
                }

                else
                ///////////////////CHAR///////////////////

                //start character
                if (s[i] == '\'')
                {
                    int n = 1;
                    i++;
                    //file length checking
                    if (s.Length <= i)
                    {
                        //Console.WriteLine("({0},{1},{2})", "Laxical Error", "_", line);
                        allow = 1;
                        //Console.WriteLine("Ending File");
                        break;
                    }

                    //('')char error checking
                    if (s[i] == '\'')
                    {
                        temp  = temp + s[i];
                        allow = 1;

                        //Console.WriteLine("({0},{1},{2})", "Laxical Error", "_", line);
                    }
                    //character ending checking
                    while (s[i] != '\'')
                    {
                        n++;

                        if (n == 4 || n == 3)
                        {
                            allow = 1;

                            // Console.WriteLine("({0},{1},{2})", "Laxical Error", "_", line);

                            break;
                        }
                        // (with \)char checking
                        if (s[i] == '\\')
                        {
                            i++;
                            n++;
                            if (s[i] == ' ')
                            {
                                //Console.WriteLine("Error of space after \\ ");
                                //Console.WriteLine("({0},{1},{2})", "Laxical Error", "_", line);
                                temp = temp + s[i];
                                break;
                            }
                            else
                            // (with \ enter)char error checking

                            if (s[i] == '\r')
                            {
                                allow = 1;


                                // Console.WriteLine("error of enter after \\ ");
                                // Console.WriteLine("({0},{1},{2})", "Laxical Error", "_", line);
                                e = 1;
                                --i;
                                break;
                            }
                            else
                            {
                                temp = temp + s[i];
                            }
                        }
                        else

                        if (s[i] == '\r')
                        {
                            allow = 1;

                            // Console.WriteLine("Enter Error without \\");
                            //  Console.WriteLine("({0},{1},{2})", "Laxical Error", "_", line);
                            e = 1;
                            --i;
                            break;
                        }
                        else
                        {
                            temp = temp + s[i];
                        }
                        i++;
                        //length error
                        if (s.Length == i)
                        {
                            allow = 1;
                            // Console.WriteLine("({0},{1},{2})", "Laxical Error", "_", line);

                            // Console.WriteLine("Ending File");
                            break;
                        }
                    }
                    if (allow == 0)
                    {
                        Console.WriteLine("{0} {1} {2}", "Char", temp, line);
                        file.WriteLine("{0} {1} {2}", "CHAR_CONST", temp, line);
                    }
                    else if (allow == 1)
                    {
                        Console.WriteLine("{0} {1} {2}", "Invalid", temp, line);
                        file.WriteLine("{0} {1} {2}", "Invalid", temp, line);
                    }
                }

                else
                /////////////////INTEGER///////////

                if (s[i] == '-' || s[i] == '+' || intvalues.ContainsKey(s[i]) || DOT.ContainsKey(s[i]))
                {
                    if (s[i] == '-' || s[i] == '+')

                    {
                        if (!intvalues.ContainsKey(s[++i]))
                        {
                            --i;

                            temp = temp + s[i];
                            ++i;
                            if (s.Length == i)
                            {
                                Console.WriteLine("{0} {1} {2}", PM[temp], temp, line);
                                file.WriteLine("{0} {1} {2}", PM[temp], temp, line);


                                break;
                            }

                            if (PM.ContainsKey(s[i].ToString()) && s[i].ToString() == temp)
                            {
                                temp = temp + s[i];

                                Console.WriteLine("{0} {1} {2}", INC[temp], temp, line);
                                file.WriteLine("{0} {1} {2}", INC[temp], temp, line);
                            }
                            else if (SIGNOP.ContainsKey(s[i].ToString()))
                            {
                                temp = temp + s[i];
                                Console.WriteLine("{0} {1} {2}", SIGNOP[temp], temp, line);
                                file.WriteLine("{0} {1} {2}", SIGNOP[temp], temp, line);

                                //++i;
                            }
                            else
                            {
                                Console.WriteLine("{0} {1} {2}", PM[temp], temp, line);
                                file.WriteLine("{0} {1} {2}", PM[temp], temp, line);


                                --i;
                            }
                            if (s[i] == '\r')
                            {
                                e = 1;
                                break;
                            }
                        }
                        else
                        {
                            c = s[--i];
                        }
                    }
                    if (s.Length <= i)
                    {
                        if ((intvalues.ContainsKey(s[++i])))
                        {
                            Console.WriteLine("{0} {1} {2}", s[i], s[i], line);
                            file.WriteLine("{0} {1} {2}", s[i], s[i], line);


                            break;
                        }
                        --i;
                    }


                    if (intvalues.ContainsKey(s[i]) || DOT.ContainsKey(s[i]))
                    {
                        temp = temp + c;

                        while (!(s[i] == ' ' || SIGNOP.ContainsKey(s[i].ToString()) || PM.ContainsKey(s[i].ToString()) || MDM.ContainsKey(s[i].ToString()) || RO.ContainsKey(s[i].ToString()) || PUNCTUATOR.ContainsKey(s[i].ToString()) || s[i] == '\r'))
                        {
                            if (!(intvalues.ContainsKey(s[i]) || DOT.ContainsKey(s[i])))
                            {
                                while (!(s[i] == ' ' || SIGNOP.ContainsKey(s[i].ToString()) || PUNCTUATORS.ContainsKey(s[i].ToString()) || PM.ContainsKey(s[i].ToString()) || MDM.ContainsKey(s[i].ToString()) || RO.ContainsKey(s[i].ToString()) || s[i] == '\r'))
                                {
                                    temp = temp + s[i];
                                    i++;
                                    if (s.Length == i)
                                    {
                                        break;
                                    }
                                    if (s[i] == '\r')
                                    {
                                        e = 1;
                                    }
                                }

                                allow = 1;
                                //  Console.WriteLine("({0},{1},{2})", "Laxical Errors", "_", line);


                                break;
                            }
                            else
                            {
                                //Console.WriteLine(s[i]);

                                temp = temp + s[i];

                                if (s[i] == '.')
                                {
                                    dotCounter++;
                                    ++i;



                                    if (dotCounter >= 2)
                                    {
                                        // Console.WriteLine("({0},{1},{2})", "Laxical Error", "_", line);
                                        allow = 1;
                                        //Console.WriteLine("float cannot conatin more than one dot");
                                    }
                                    if (s.Length == i)
                                    {
                                        // Console.WriteLine("({0},{1},{2})", "Laxical Error", "_", line);
                                        allow = 1;
                                        break;
                                    }
                                    if (s[i] == ' ')
                                    {
                                        //   Console.WriteLine("({0},{1},{2})", "Laxical Error", "_", line);
                                        allow = 1;
                                        // Console.WriteLine("Error");
                                        break;
                                    }
                                    --i;
                                }

                                i++;
                                if (s.Length == i)
                                {
                                    break;
                                }
                            }
                        }
                        --i;

                        if (allow == 0)
                        {
                            if (temp.Contains('.'))
                            {
                                Console.WriteLine("{0} {1} {2}", "FLOAT_CONST", temp, line);
                                file.WriteLine("{0} {1} {2}", "FLOAT_CONST", temp, line);
                            }
                            else
                            {
                                Console.WriteLine("{0} {1} {2}", "INT_CONST", temp, line);
                                file.WriteLine("{0} {1} {2}", "INT_CONST", temp, line);
                            }
                        }

                        if (allow == 1)
                        {
                            Console.WriteLine("{0} {1} {2}", "Invalids", temp, line);
                            file.WriteLine("{0} {1} {2}", "Invalid", temp, line);
                        }
                    }
                }

                else
                //////IDENTIFIER/////


                if (s[i] == '_')
                {
                    i++;

                    if (s.Length == i || s[i] == ' ')
                    {
                        temp = temp + s[--i];
                        //  Console.WriteLine("({0},{1},{2})", "Laxical Errors", "_", line);
                        allow = 1;
                    }
                    else
                    if (intvalues.ContainsKey(s[i]))
                    {
                        temp = temp + s[--i];
                        ++i;
                        while (!(s[i] == ' ' || SIGNOP.ContainsKey(s[i].ToString())))
                        {
                            temp = temp + s[i];
                            i++;
                            if (s.Length == i)
                            {
                                break;
                            }
                        }

                        //    Console.WriteLine("({0},{1},{2})", "Laxical Error"+temp, "_", line);
                        allow = 1;
                        // Console.WriteLine("Error");
                    }
                    else
                    {
                        --i;
                        //
                        //while (!(s[i] == ' ' || SIGNOP.ContainsKey(s[i].ToString()) || PM.ContainsKey(s[i].ToString()) || MDM.ContainsKey(s[i].ToString()) || RO.ContainsKey(s[i].ToString()) || s[i]=='\r' ))
                        while ((s[i] >= 'A' && s[i] <= 'Z') || (intvalues.ContainsKey(s[i])) || (s[i] >= 'a' && s[i] <= 'z') || (s[i] == '_'))
                        {
                            temp = temp + s[i];
                            i++;
                            if (s.Length == i)
                            {
                                break;
                            }
                            if (s[i] == '\r')
                            {
                                e = 1;
                            }
                        }

                        --i;

                        if (allow == 0)
                        {
                            Console.WriteLine("{0} {1} {2}", "ID", temp, line);
                            file.WriteLine("{0} {1} {2}", "ID", temp, line);
                        }
                    }
                    if (allow == 1)
                    {
                        Console.WriteLine("{0} {1} {2}", "invalid", temp, line);
                        file.WriteLine("{0} {1} {2}", "Invalid", temp, line);
                    }
                }
                //assign operater
                else if (SIGNOP.ContainsKey(s[i].ToString()))
                {
                    temp = temp + s[i];

                    ++i;
                    if (s.Length == i)
                    {
                        Console.WriteLine("{0} {1} {2}", SIGNOP[temp], temp, line);
                        file.WriteLine("{0} {1} {2}", SIGNOP[temp], temp, line);



                        break;
                    }
                    if (s[i] == '\r')
                    {
                        e = 1;
                    }

                    if (SIGNOP.ContainsKey(s[i].ToString()))
                    {
                        temp = temp + s[i];
                        Console.WriteLine("{0} {1} {2}", RO[temp], temp, line);
                        file.WriteLine("{0} {1} {2}", RO[temp], temp, line);
                    }
                    else
                    {
                        Console.WriteLine("{0} {1} {2}", SIGNOP[temp], temp, line);
                        file.WriteLine("{0} {1} {2}", SIGNOP[temp], temp, line);

                        --i;
                    }
                }

                //Plus Minus OR With Asign Operater
                else if (PM.ContainsKey(s[i].ToString()))
                {
                    temp = temp + s[i];
                    ++i;
                    if (s.Length == i)
                    {
                        Console.WriteLine("{0} {1} {2}", PM[temp], temp, line);
                        file.WriteLine("{0} {1} {2}", PM[temp], temp, line);


                        break;
                    }

                    if (PM.ContainsKey(s[i].ToString()))
                    {
                        temp = temp + s[i];

                        Console.WriteLine("{0} {1} {2}", INC[temp], temp, line);
                        file.WriteLine("{0} {1} {2}", INC[temp], temp, line);
                    }
                    else if (SIGNOP.ContainsKey(s[i].ToString()))
                    {
                        temp = temp + s[i];
                        Console.WriteLine("{0} {1} {2}", SIGNOP[temp], temp, line);
                        file.WriteLine("{0} {1} {2}", SIGNOP[temp], temp, line);
                    }
                    else
                    {
                        Console.WriteLine("{0} {1} {2}", PM[temp], temp, line);
                        file.WriteLine("{0} {1} {2}", PM[temp], temp, line);

                        --i;
                    }

                    if (s[i] == '\r')
                    {
                        e = 1;
                    }
                }
                //MDM With or without asign operator
                else if (MDM.ContainsKey(s[i].ToString()))
                {
                    temp = temp + s[i];
                    ++i;

                    if (s.Length == i)
                    {
                        Console.WriteLine("{0} {1} {2}", MDM[temp], temp, line);
                        file.WriteLine("{0} {1} {2}", MDM[temp], temp, line);


                        break;
                    }



                    if (SIGNOP.ContainsKey(s[i].ToString()))
                    {
                        temp = temp + s[i];
                        Console.WriteLine("{0} {1} {2}", SIGNOP[temp], temp, line);
                        file.WriteLine("{0} {1} {2}", SIGNOP[temp], temp, line);
                    }
                    else
                    {
                        Console.WriteLine("{0} {1} {2}", MDM[temp], temp, line);
                        file.WriteLine("{0} {1} {2}", MDM[temp], temp, line);

                        --i;
                    }
                    if (s[i] == '\r')
                    {
                        e = 1;
                    }
                }

                ///RO
                else if (RO.ContainsKey(s[i].ToString()))
                {
                    temp = temp + s[i];

                    ++i;

                    if (s.Length == i)
                    {
                        Console.WriteLine("{0} {1} {2}", RO[temp], temp, line);
                        file.WriteLine("{0} {1} {2}", RO[temp], temp, line);


                        break;
                    }



                    if (SIGNOP.ContainsKey(s[i].ToString()))
                    {
                        temp = temp + s[i];
                        Console.WriteLine("{0} {1} {2}", RO[temp], temp, line);
                        file.WriteLine("{0} {1} {2}", RO[temp], temp, line);
                    }
                    else
                    {
                        Console.WriteLine("{0} {1} {2}", RO[temp], temp, line);
                        file.WriteLine("{0} {1} {2}", RO[temp], temp, line);

                        --i;
                    }
                    if (s[i] == '\r')
                    {
                        e = 1;
                    }
                }


                ///Punctuators
                else if (PUNCTUATORS.ContainsKey(s[i].ToString()))
                {
                    temp = temp + s[i];
                    Console.WriteLine("{0} {1} {2}", temp, temp, line);
                    file.WriteLine("{0} {1} {2}", temp, temp, line);
                }


                else
                {
                    while (!(s[i] == ' ' || PUNCTUATORS.ContainsKey(s[i].ToString()) || s[i] == '\r' || s[i] == '"' || s[i] == '\'' || SIGNOP.ContainsKey(s[i].ToString()) || RO.ContainsKey(s[i].ToString()) || PM.ContainsKey(s[i].ToString()) ||
                             intvalues.ContainsKey(s[i]) || KEYWORDS.ContainsKey(temp) ||
                             INC.ContainsKey(temp) || LO.ContainsKey(temp) || s[i] == '_' || MDM.ContainsKey(s[i].ToString())))
                    {
                        if (s[i] != ' ')
                        {
                            // Console.WriteLine(s[i]);
                            temp = temp + s[i];
                            temp = Regex.Replace(temp, @"\s", "");
                            //temp= temp.Replace(" ", string.Empty);
                        }
                        //  Console.WriteLine(temp);
                        ++i;



                        if (s.Length == i)
                        {
                            break;
                        }
                        //if (PUNCTUATORS.ContainsKey(s[i].ToString()))
                        //{
                        //    --i;
                        //    break;
                        //}

                        if (s[i] == '\r')
                        {
                            e = 1;

                            break;
                        }
                    }
                    --i;



                    if (KEYWORDS.ContainsKey(temp))
                    {
                        Console.WriteLine("{0} {1} {2}", KEYWORDS[temp], temp, line);
                        file.WriteLine("{0} {1} {2}", KEYWORDS[temp], temp, line);
                    }

                    else
                    {
                        if (!(s[i] != ' ' || s[i] != '\r'))
                        {
                            Console.WriteLine("{0} {1} {2}", "Invalid", temp, line);
                            file.WriteLine("{0} {1} {2}", "Invalid", temp, line);
                        }
                    }
                }
            }

            file.Dispose();
        }
Esempio n. 57
0
 public override void Initialize()
 {
     this.m_effects = base.Database.Fetch <EffectTemplate>(EffectTemplateRelator.FetchQuery, new object[0]).ToDictionary((EffectTemplate entry) => (short)entry.Id);
     this.InitializeEffectHandlers();
     this.InitializeTargetMaskHandlers();
 }
Esempio n. 58
0
        public static System.Collections.Generic.Dictionary <int, string> getButtonsHtml(string menuID = "", string subpageID = "", string programID = "")
        {
            Guid menuID1;

            if (menuID.IsNullOrEmpty() || !menuID.IsGuid(out menuID1))
            {
                menuID1 = HttpContext.Current.Request.QueryString["appid"].ToGuid();
            }
            Guid subpageID1;

            if (!subpageID.IsGuid(out subpageID1))
            {
                subpageID1 = HttpContext.Current.Request.QueryString["subpageid"].ToGuid();
            }
            System.Collections.Generic.Dictionary <int, string> dictionary = new System.Collections.Generic.Dictionary <int, string>();
            dictionary.Add(0, "");
            dictionary.Add(1, "");
            dictionary.Add(2, "");
            string      str1     = HttpContext.Current.Request.QueryString["applibaryid"];
            List <Guid> guidList = new List <Guid>();

            if (str1.IsGuid())
            {
                foreach (RoadFlow.Data.Model.AppLibraryButtons1 appLibraryButtons1 in new AppLibraryButtons1().GetAllByAppID(str1.ToGuid()).FindAll((Predicate <RoadFlow.Data.Model.AppLibraryButtons1>)(p => p.IsValidateShow == 1)))
                {
                    guidList.Add(appLibraryButtons1.ID);
                }
            }
            else
            {
                foreach (RoadFlow.Data.Model.MenuUser menuUser in new MenuUser().GetAll(true).FindAll((Predicate <RoadFlow.Data.Model.MenuUser>)(p =>
                {
                    if (p.MenuID == menuID1 && p.SubPageID == subpageID1)
                    {
                        return(p.Users.Contains(Users.CurrentUserID.ToString(), StringComparison.CurrentCultureIgnoreCase));
                    }
                    return(false);
                })))
                {
                    string buttons = menuUser.Buttons;
                    char[] chArray = new char[1] {
                        ','
                    };
                    foreach (string str2 in buttons.Split(chArray))
                    {
                        Guid test;
                        if (str2.IsGuid(out test) && !guidList.Contains(test))
                        {
                            guidList.Add(test);
                        }
                    }
                }
            }
            List <RoadFlow.Data.Model.AppLibraryButtons1> source = new List <RoadFlow.Data.Model.AppLibraryButtons1>();

            RoadFlow.Data.Model.AppLibrary byCode = new AppLibrary().GetByCode(programID, true);
            if (byCode != null)
            {
                source.AddRange((IEnumerable <RoadFlow.Data.Model.AppLibraryButtons1>) new AppLibraryButtons1().GetAllByAppID(byCode.ID).FindAll((Predicate <RoadFlow.Data.Model.AppLibraryButtons1>)(p => p.IsValidateShow == 0)));
            }
            if (guidList.Count == 0 && source.Count == 0)
            {
                return(dictionary);
            }
            StringBuilder      stringBuilder1       = new StringBuilder();
            StringBuilder      stringBuilder2       = new StringBuilder();
            StringBuilder      stringBuilder3       = new StringBuilder();
            AppLibraryButtons1 appLibraryButtons1_1 = new AppLibraryButtons1();

            foreach (Guid id in guidList)
            {
                RoadFlow.Data.Model.AppLibraryButtons1 appLibraryButtons1_2 = appLibraryButtons1_1.Get(id, true);
                if (appLibraryButtons1_2 != null && appLibraryButtons1_2.IsValidateShow != 0)
                {
                    source.Add(appLibraryButtons1_2);
                }
            }
            foreach (RoadFlow.Data.Model.AppLibraryButtons1 appLibraryButtons1_2 in (IEnumerable <RoadFlow.Data.Model.AppLibraryButtons1>)source.OrderBy <RoadFlow.Data.Model.AppLibraryButtons1, int>((Func <RoadFlow.Data.Model.AppLibraryButtons1, int>)(p => p.Sort)))
            {
                string userID = Users.CurrentUserID.ToString();
                if (appLibraryButtons1_2.ShowType == 0)
                {
                    string str2 = "fun_" + Guid.NewGuid().ToString("N");
                    stringBuilder1.Append("<a href=\"javascript:void(0);\" onclick=\"" + str2 + "();return false;\"><span style=\"" + (appLibraryButtons1_2.Ico.IsNullOrEmpty() || appLibraryButtons1_2.Ico.IsFontIco() ? "padding-left:0px;" : "background-image:url(" + Config.BaseUrl + appLibraryButtons1_2.Ico + ");") + "\">" + (appLibraryButtons1_2.Ico.IsNullOrEmpty() || !appLibraryButtons1_2.Ico.IsFontIco() ? "" : "<i class='fa " + appLibraryButtons1_2.Ico + "' style='font-size:14px;vertical-align:middle;margin-right:3px;'></i>") + appLibraryButtons1_2.Name + "</span></a>");
                    stringBuilder1.Append("<script type=\"text/javascript\">function " + str2 + "(){" + appLibraryButtons1_2.Events.FilterWildcard(userID) + "}</script>");
                }
                else if (appLibraryButtons1_2.ShowType == 1)
                {
                    string str2 = "fun_" + Guid.NewGuid().ToString("N");
                    stringBuilder2.Append("<button type=\"button\" " + (appLibraryButtons1_2.Ico.IsNullOrEmpty() ? "style=\"margin-left:6px;\"" : "style=\"margin-left:6px;" + (appLibraryButtons1_2.Ico.IsNullOrEmpty() || appLibraryButtons1_2.Ico.IsFontIco() ? "" : "background-image:url(" + Config.BaseUrl + appLibraryButtons1_2.Ico + ");background-repeat:no-repeat;background-position-y:center;background-position-x:8px;padding-left:28px;") + "\"") + " onclick=\"" + str2 + "();return false;\" class=\"mybutton\">");
                    if (!appLibraryButtons1_2.Ico.IsNullOrEmpty() && appLibraryButtons1_2.Ico.IsFontIco())
                    {
                        stringBuilder2.Append("<i class=\"fa " + appLibraryButtons1_2.Ico + "\" style=\"font-size:14px;vertical-align:middle;margin-right:3px;\"></i>");
                    }
                    stringBuilder2.Append("<span style=\"vertical-align:middle;\">" + appLibraryButtons1_2.Name + "</span>");
                    stringBuilder2.Append("</button>");
                    stringBuilder2.Append("<script type=\"text/javascript\">function " + str2 + "(){" + appLibraryButtons1_2.Events.FilterWildcard(userID) + "}</script>");
                }
                else if (appLibraryButtons1_2.ShowType == 2)
                {
                    string str2 = "fun_" + Guid.NewGuid().ToString("N");
                    stringBuilder3.Append("<a href=\"javascript:void(0);\" onclick=\"" + appLibraryButtons1_2.Events + ";return false;\" " + (appLibraryButtons1_2.Ico.IsNullOrEmpty() ? "style=\"margin-left:0px;\"" : "style=\"margin-left:0px;" + (!appLibraryButtons1_2.Ico.IsFontIco() ? "padding-left:26px;background-image:url(" + Config.BaseUrl + appLibraryButtons1_2.Ico + ");background-repeat:no-repeat;background-position-y:center;background-position-x:8px;" : "") + "\"") + ">" + (appLibraryButtons1_2.Ico.IsNullOrEmpty() || !appLibraryButtons1_2.Ico.IsFontIco() ? "" : "<i class='fa " + appLibraryButtons1_2.Ico + "' style='font-size:14px;vertical-align:middle;margin-right:3px;padding-left:10px;'></i>") + appLibraryButtons1_2.Name + "</a>");
                }
            }
            dictionary[0] = stringBuilder1.Length > 0 ? "<div class=\"toolbar\" style=\"margin-top:0; border-top:none 0; position:fixed; top:0; left:0; right:0; margin-left:auto; z-index:999; width:100%; margin-right:auto;\">" + stringBuilder1.ToString() + "</div>" : "";
            dictionary[1] = stringBuilder2.ToString();
            dictionary[2] = stringBuilder3.ToString();
            return(dictionary);
        }
        static void Main()
        {
            // Enable Unicode
            Console.OutputEncoding = Encoding.Unicode;

            // тестування роботи словника на тому, що
            // якщо буде випадок, що ключ заданий типом int
            // і є два індекатори з доступом по ключу і доступом по індексу
            // який же індексатор обереться

            // створюємо словник
            Dictionary <int, string> dictionary = new Dictionary <int, string>();

            // скористаємося послідовністю Фібоначчі, на якій базується золотий перетин
            // https://uk.wikipedia.org/wiki/Послідовність_Фібоначчі
            // 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144
            int[] fibonachi = new int[]
            {
                0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144
            };

            var dayOfWeek = Enum.GetValues(typeof(DayOfWeek))
                            .Cast <DayOfWeek>().ToArray();

            // заповнення масива даними
            for (int i = 0; i < dayOfWeek.Length; i++)
            {
                dictionary.Add(fibonachi[i], dayOfWeek[i].ToString());
            }

            // Результат словника
            Console.WriteLine("\n\tДані словника:\n");
            Console.WriteLine(dictionary.ToString());

            // тестування
            Console.WriteLine("\n\tСпроба звернутися за індексом: 4");
            Console.WriteLine($"\tkey: {4}, value: {dictionary[4]};\n");

            Console.WriteLine("\tСпроба звернутися за індексом: 8");
            Console.WriteLine($"\tkey: {8}, value: {dictionary[8]};\n");

            Console.WriteLine(new string('#', 80));

            // Висновок. Якщо в словника ключ типу int,
            // то домінує індесатор з доступом по індексу, а не по ключу

            // тестування методу на вбудованому словнику

            System.Collections.Generic.Dictionary <int, string> pairs =
                new System.Collections.Generic.Dictionary <int, string>();

            // заповнення масива даними
            Console.WriteLine("\n\tДані вбудованого словника:\n");

            for (int i = 2; i < dayOfWeek.Length + 2; i++)
            {
                pairs.Add(fibonachi[i], dayOfWeek[i - 2].ToString());
                Console.WriteLine($"\tkey: {fibonachi[i]}, value: {dayOfWeek[i - 2].ToString()};");
            }

            // тестування
#if false
            Console.WriteLine("\n\tСпроба звернутися за індексом: 4");
            Console.WriteLine($"\tkey: {4}, value: {pairs[4]};\n");
#endif

            // у вбудованому словнику доступ відбувається
            // лише по ключу, а доступ по індексу: pairs.ElementAt(4);

            // repeat
            DoExitOrRepeat();
        }
Esempio n. 60
0
    void Start()
    {
        if (SceneManager.GetActiveScene().name != "Desktop")
        {
            leftSide = GameObject.FindWithTag("BorderLeft").transform;
        }
        //Create a Dictionary to contain all our Objects/Transforms
        System.Collections.Generic.Dictionary <string, Transform> colliders = new System.Collections.Generic.Dictionary <string, Transform>();
        //Create our GameObjects and add their Transform components to the Dictionary we created above
        colliders.Add("Top", new GameObject().transform);
        colliders.Add("Bottom", new GameObject().transform);
        colliders.Add("Right", new GameObject().transform);
        colliders.Add("Left", new GameObject().transform);
        //Generate world space point information for position and scale calculations
        Vector3 cameraPos = Camera.main.transform.position;

        //Grab the world-space position values of the start and end positions of the screen,
        //then calculate the distance between them and store it as half, since we only need
        //half that value for distance away from the camera to the edge
        screenSize.x = Vector2.Distance(Camera.main.ScreenToWorldPoint(new Vector2(0, 0)), Camera.main.ScreenToWorldPoint(new Vector2(Screen.width, 0))) * 0.5f;
        screenSize.y = Vector2.Distance(Camera.main.ScreenToWorldPoint(new Vector2(0, 0)), Camera.main.ScreenToWorldPoint(new Vector2(0, Screen.height))) * 0.5f;
        //For each Transform/Object in our Dictionary
        foreach (KeyValuePair <string, Transform> valPair in colliders)
        {
            //Add our colliders. Remove the "2D", if you would like 3D colliders.
            valPair.Value.gameObject.AddComponent <BoxCollider>();
            //Set the object's name to it's "Key" name, and take on "Collider".  i.e: TopCollider
            valPair.Value.name = valPair.Key + "Collider";
            //Make the object a child of whatever object this script is on (preferably the camera)
            valPair.Value.parent = transform;
            //Scale the object to the width and height of the screen, using the world-space values calculated earlier
            valPair.Value.gameObject.layer = layer;
            if (valPair.Key == "Left" || valPair.Key == "Right")
            {
                valPair.Value.localScale = new Vector3(colThickness, screenSize.y * 200, colZWidth);
            }
            else
            {
                valPair.Value.localScale = new Vector3(screenSize.x * 2, colThickness, colZWidth);
            }
            //We add the Physicsmaterial to the collider here if there is any
            //Remove the 2D from BoxCollider2D if you are working with 3D
            if (physicsMaterial)
            {
                valPair.Value.gameObject.GetComponent <BoxCollider>().sharedMaterial = physicsMaterial;
            }
        }
        //Change positions to align perfectly with outter-edge of screen,
        //adding the world-space values of the screen we generated earlier,
        //and adding/subtracting them with the current camera position,
        //as well as add/subtracting half out objects size so it's not just half way off-screen
        colliders["Right"].position  = new Vector3(cameraPos.x + screenSize.x + (colliders["Right"].localScale.x * 0.5f), cameraPos.y, zPosition);
        colliders["Left"].position   = new Vector3(cameraPos.x - screenSize.x - (colliders["Left"].localScale.x * 0.5f), cameraPos.y, zPosition);
        colliders["Top"].position    = new Vector3(cameraPos.x, cameraPos.y + screenSize.y * 99.6f + (colliders["Top"].localScale.y * 0.5f), zPosition);
        colliders["Bottom"].position = new Vector3(cameraPos.x, cameraPos.y - screenSize.y - (colliders["Bottom"].localScale.y * 0.5f), zPosition);
        //colliders["Top"].gameObject.SetActive(false);
        if (leftSide != null)
        {
            leftSide.position = new Vector3(colliders["Left"].position.x + (colThickness / 2) - (leftSide.localScale.y / 2), leftSide.position.y, leftSide.position.z);
        }
    }