/// <summary>Sends a notification to a set of users.</summary>
 /// <param name="toIds">Comma-separated list of recipient IDs. These must be either friends of the logged-in user or people who have added your application. To send a notification to the current logged-in user without a name prepended to the message, set <code>to_ids</code> to the empty string.</param>
 /// <param name="notification"><a href="/index.php/FBML" title="FBML">FBML</a> for the notifications page. Uses a stripped down version allowing only text and links.</param>
 public FacebookResponse<String> Send(String[] toIds, String notification) {
     System.Collections.Generic.Dictionary<string, object> args = new System.Collections.Generic.Dictionary<string, object>();
     args.Add("to_ids", toIds);
     args.Add("notification", notification);
     var response = this.ExecuteRequest<String>("Notifications.send", args);
     return response;
 }
Ejemplo n.º 2
0
 /// <summary>Builds a template bundle around the specified templates, registers them on Facebook, and responds with a template bundle ID that can be used to identify your template bundle to other Feed-related API calls.</summary>
 /// <param name="oneLineStoryTemplates">A JSON-encoded array containing one FBML template that can be used to render one line Feed stories.</param>
 /// <param name="shortStoryTemplates">A JSON-encoded array containing an object, which represents a short story template.  The dictionary should include two fields: <code>template_title</code>, which should be mapped to the FBML template used to render a short story's title, and <code>template_body</code>, which should map to the FBML template used to render a short story's body. The token set of a short story template is taken to be the union of the <code>template_title</code> and the <code>template_body</code> templates.</param>
 public FacebookResponse<Int64> RegisterTemplateBundle(String[] oneLineStoryTemplates, String[] shortStoryTemplates) {
     System.Collections.Generic.Dictionary<string, object> args = new System.Collections.Generic.Dictionary<string, object>();
     args.Add("one_line_story_templates", oneLineStoryTemplates);
     args.Add("short_story_templates", shortStoryTemplates);
     var response = this.ExecuteRequest<Int64>("Feed.registerTemplateBundle", args);
     return response;
 }
 /// <summary>Returns whether or not each pair of specified users is friends with each other.</summary>
 /// <param name="uids1">A list of user IDs matched with <code>uids2</code>. This is a comma-separated list of user IDs.</param>
 /// <param name="uids2">A list of user IDs matched with <code>uids1</code>. This is a comma-separated list of user IDs.</param>
 public FacebookResponse<FacebookList<FriendInfo>> AreFriends(String[] uids1, String[] uids2) {
     System.Collections.Generic.Dictionary<string, object> args = new System.Collections.Generic.Dictionary<string, object>();
     args.Add("uids1", uids1);
     args.Add("uids2", uids2);
     var response = this.ExecuteRequest<FacebookList<FriendInfo>>("Friends.areFriends", args);
     return response;
 }
Ejemplo n.º 4
0
 /// <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;
 }
Ejemplo n.º 5
0
    public static void btnIniciar_onclick(string mail, string pass)
    {
        //HttpContext.Current.Session["user"] = "******";
        //return;
        if (validar( mail,  pass))
        {
            //revisar que los datos existan
            Dictionary<string, object> parameters = new System.Collections.Generic.Dictionary<string, object>();
            parameters.Add("@mail", mail);
            parameters.Add("@pass", pass);
            DataTable dt = null;
            dt = DataAccess.executeStoreProcedureDataTable("spr_GET_IniciarSesion", parameters);
            try
            {
                if (dt != null && dt.Rows.Count > 0)
                {
                    string result = dt.Rows[0]["result"].ToString();
                    HttpContext.Current.Session["err"] = result;
                    HttpContext.Current.Session["user"] = null;
                    if (result == "puedePasar")
                    {
                        HttpContext.Current.Session["user"] = dt.Rows[0]["nikname"].ToString().Trim();
                        HttpContext.Current.Session["findOut"] = dt.Rows[0]["findOut"].ToString().Trim();
                        HttpContext.Current.Session["idEmpresa"] = dt.Rows[0]["idEmpresa"].ToString().Trim();
                    }
                }
            }
            catch (Exception ex) {

            }
        }
    }
Ejemplo n.º 6
0
        public void ProcessRequest(HttpContext context)
        {
            NFMT.Common.UserModel user = Utility.UserUtility.CurrentUser;

            int pageIndex = 1, pageSize = 10;
            string orderStr = string.Empty, whereStr = string.Empty;

            int customerCorpId = 0;
            if (!string.IsNullOrEmpty(context.Request.QueryString["corpId"]))
            {
                if (!int.TryParse(context.Request.QueryString["corpId"], out customerCorpId))
                    customerCorpId = 0;
            }

            DateTime beginDate = NFMT.Common.DefaultValue.DefaultTime;
            DateTime endDate = NFMT.Common.DefaultValue.DefaultTime;

            if (!string.IsNullOrEmpty(context.Request["db"]))
            {
                if (!DateTime.TryParse(context.Request["db"], out beginDate))
                    beginDate = NFMT.Common.DefaultValue.DefaultTime;
            }
            if (!string.IsNullOrEmpty(context.Request["de"]))
            {
                if (!DateTime.TryParse(context.Request["de"], out endDate))
                    endDate = NFMT.Common.DefaultValue.DefaultTime;
                else
                    endDate = endDate.AddDays(1);
            }

            if (!string.IsNullOrEmpty(context.Request.QueryString["pagenum"]))
                int.TryParse(context.Request.QueryString["pagenum"], out pageIndex);
            pageIndex++;
            if (!string.IsNullOrEmpty(context.Request.QueryString["pagesize"]))
                int.TryParse(context.Request.QueryString["pagesize"], out pageSize);

            if (!string.IsNullOrEmpty(context.Request.QueryString["sortdatafield"]) && !string.IsNullOrEmpty(context.Request.QueryString["sortorder"]))
                orderStr = string.Format("{0} {1}", context.Request.QueryString["sortdatafield"].Trim(), context.Request.QueryString["sortorder"].Trim());

            NFMT.Invoice.BLL.InvoiceApplyBLL bll = new NFMT.Invoice.BLL.InvoiceApplyBLL();
            NFMT.Common.SelectModel select = bll.GetCanApplySISelectModel(pageIndex, pageSize, orderStr, customerCorpId, beginDate, endDate);
            NFMT.Common.ResultModel result = bll.Load(user, select);

            context.Response.ContentType = "application/json; charset=utf-8";
            if (result.ResultStatus != 0)
            {
                context.Response.Write(result.Message);
                context.Response.End();
            }

            System.Data.DataTable dt = result.ReturnValue as System.Data.DataTable;
            System.Collections.Generic.Dictionary<string, object> dic = new System.Collections.Generic.Dictionary<string, object>();

            dic.Add("count", result.AffectCount);
            dic.Add("data", dt);

            string postData = Newtonsoft.Json.JsonConvert.SerializeObject(dic);

            context.Response.Write(postData);
        }
 /// <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;
 }
Ejemplo n.º 8
0
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "application/json; charset=utf-8";
            NFMT.Common.UserModel user = Utility.UserUtility.CurrentUser;

            int sIId = 0;
            if (string.IsNullOrEmpty(context.Request.QueryString["sIId"]) || !int.TryParse(context.Request.QueryString["sIId"], out sIId))
                sIId = 0;

            NFMT.Invoice.BLL.SIDetailBLL sIDetailBLL = new NFMT.Invoice.BLL.SIDetailBLL();
            NFMT.Common.ResultModel result = sIDetailBLL.GetSIDetailForUpdate(user, sIId);
            context.Response.ContentType = "application/json; charset=utf-8";
            if (result.ResultStatus != 0)
            {
                context.Response.Write(result.Message);
                context.Response.End();
            }

            System.Data.DataTable dt = result.ReturnValue as System.Data.DataTable;
            System.Collections.Generic.Dictionary<string, object> dic = new System.Collections.Generic.Dictionary<string, object>();

            dic.Add("count", dt.Rows.Count);
            dic.Add("data", dt);

            string postData = Newtonsoft.Json.JsonConvert.SerializeObject(dic);
            context.Response.Write(postData);
        }
Ejemplo n.º 9
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];
                    }
                );
        }
Ejemplo n.º 10
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);
            }
        }
Ejemplo n.º 11
0
 /// <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;
 }
Ejemplo n.º 12
0
 /// <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;
 }
Ejemplo n.º 13
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);
		}
Ejemplo n.º 14
0
 /// <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;
 }
Ejemplo n.º 15
0
 /// <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;
 }
Ejemplo n.º 16
0
 /// <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;
 }
Ejemplo n.º 17
0
 /// <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;
 }
Ejemplo n.º 18
0
 /// <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;
 }
Ejemplo n.º 19
0
 /// <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;
 }
Ejemplo n.º 20
0
 /// <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;
 }
        public void ProcessRequest(HttpContext context)
        {
            NFMT.Common.UserModel user = Utility.UserUtility.CurrentUser;

            int pageIndex = 1, pageSize = 10;
            string orderStr = string.Empty, whereStr = string.Empty;

            string stockName = context.Request.QueryString["stockName"];
            DateTime fromDate = NFMT.Common.DefaultValue.DefaultTime;
            DateTime toDate = NFMT.Common.DefaultValue.DefaultTime;
            int status = 0;

            if (!string.IsNullOrEmpty(context.Request.QueryString["status"]))
            {
                if (!int.TryParse(context.Request.QueryString["status"], out status))
                    status = 0;
            }

            if (!string.IsNullOrEmpty(context.Request.QueryString["fromDate"]))
            {
                if (!DateTime.TryParse(context.Request.QueryString["fromDate"], out fromDate))
                    fromDate = NFMT.Common.DefaultValue.DefaultTime;
            }
            if (!string.IsNullOrEmpty(context.Request.QueryString["toDate"]))
            {
                if (!DateTime.TryParse(context.Request.QueryString["toDate"], out toDate))
                    toDate = NFMT.Common.DefaultValue.DefaultTime;
            }

            if (!string.IsNullOrEmpty(context.Request.QueryString["pagenum"]))
                int.TryParse(context.Request.QueryString["pagenum"], out pageIndex);
            pageIndex++;
            if (!string.IsNullOrEmpty(context.Request.QueryString["pagesize"]))
                int.TryParse(context.Request.QueryString["pagesize"], out pageSize);

            if (!string.IsNullOrEmpty(context.Request.QueryString["sortdatafield"]) && !string.IsNullOrEmpty(context.Request.QueryString["sortorder"]))
                orderStr = string.Format("{0} {1}", context.Request.QueryString["sortdatafield"].Trim(), context.Request.QueryString["sortorder"].Trim());

            NFMT.WareHouse.BLL.ContractStockIn_BLL bll = new NFMT.WareHouse.BLL.ContractStockIn_BLL();
            NFMT.Common.SelectModel select = bll.GetStockInNoContractSelect(pageIndex, pageSize, orderStr, stockName, status, fromDate, toDate);
            NFMT.Common.ResultModel result = bll.Load(user, select);

            context.Response.ContentType = "application/json; charset=utf-8";
            if (result.ResultStatus != 0)
            {
                context.Response.Write(result.Message);
                context.Response.End();
            }

            System.Data.DataTable dt = result.ReturnValue as System.Data.DataTable;
            System.Collections.Generic.Dictionary<string, object> dic = new System.Collections.Generic.Dictionary<string, object>();

            dic.Add("count", result.AffectCount);
            dic.Add("data", dt);

            string postData = Newtonsoft.Json.JsonConvert.SerializeObject(dic);

            context.Response.Write(postData);
        }
Ejemplo n.º 22
0
 /// <summary>Returns all visible photos according to the filters specified.</summary>
 /// <param name="subjId">Filter by photos tagged with this user. You must specify at least one of <code>subj_id</code>, <code>aid</code> or <code>pids</code>. The <code>subj_id</code> parameter has no default value, but if you pass one, it must be the user's <a href="/index.php/User_ID" title="User ID">user ID</a>.</param>
 /// <param name="aid">Filter by photos in this album. You must specify at least one of <code>subj_id</code>, <code>aid</code> or <code>pids</code>. The <code>aid</code> parameter has no default value. The <code>aid</code> cannot be longer than 50 characters.</param>
 /// <param name="pids">Filter by photos in this list. This is a comma-separated list of <code>pids</code>. You must specify at least one of <code>subj_id</code>, <code>aid</code> or <code>pids</code>. The <code>pids</code> parameter has no default value.</param>
 public FacebookResponse<FacebookList<Photo>> Get(Int64 subjId, String aid, String[] pids) {
     System.Collections.Generic.Dictionary<string, object> args = new System.Collections.Generic.Dictionary<string, object>();
     args.Add("subj_id", subjId);
     args.Add("aid", aid);
     args.Add("pids", pids);
     var response = this.ExecuteRequest<FacebookList<Photo>>("Photos.get", args);
     return response;
 }
Ejemplo n.º 23
0
 /// <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="startTime">Filter with this UTC as lower bound. A missing or zero parameter indicates no lower bound.</param>
 /// <param name="endTime">Filter with this UTC as upper bound. A missing or zero parameter indicates no upper bound.</param>
 public FacebookResponse<FacebookList<Event>> Get(Int64 uid, Int64 startTime, Int64 endTime) {
     System.Collections.Generic.Dictionary<string, object> args = new System.Collections.Generic.Dictionary<string, object>();
     args.Add("uid", uid);
     args.Add("start_time", startTime);
     args.Add("end_time", endTime);
     var response = this.ExecuteRequest<FacebookList<Event>>("Events.get", args);
     return response;
 }
Ejemplo n.º 24
0
 /// <summary>Lets a user write a Facebook note through your application.</summary>
 /// <param name="uid">The <a href="/index.php/User_ID" title="User ID">user ID</a> of the user posting the link.</param>
 /// <param name="title">The title of the note.</param>
 /// <param name="content">The note's content.</param>
 public FacebookResponse<Int64> Create(Int64 uid, String title, String content) {
     System.Collections.Generic.Dictionary<string, object> args = new System.Collections.Generic.Dictionary<string, object>();
     args.Add("uid", uid);
     args.Add("title", title);
     args.Add("content", content);
     var response = this.ExecuteRequest<Int64>("Notes.create", args);
     return response;
 }
Ejemplo n.º 25
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="generateSessionSecret">Whether to generate a temporary session secret associated with this session.  This is for use only with non-infinite sessions, for applications that want to use a client-side component without exposing the application secret.  Note that the app secret will continue to be used for all server-side calls, for security reasons.</param>
 /// <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(Boolean generateSessionSecret, String authToken) {
     System.Collections.Generic.Dictionary<string, object> args = new System.Collections.Generic.Dictionary<string, object>();
     args.Add("generate_session_secret", generateSessionSecret);
     args.Add("auth_token", authToken);
     var response = this.ExecuteRequest<SessionInfo>("Auth.getSession", args);
     if (!response.IsError) this.FacebookContext.Session.Init(response.Value);
     return response;
 }
 /// <summary>Sends a "message" directly to a user's browser, which can be handled in <a href="/index.php/FBJS" title="FBJS">FBJS</a>.</summary>
 /// <param name="recipient">The <a href="/index.php/User_ID" title="User ID">user ID</a> of the message recipient.</param>
 /// <param name="eventName">Name of the "event" for which messages will be sent and received (max length: 128 bytes).  Use this <code>event_name</code> when you initialize the <a href="/index.php/FBJS_LiveMessage" title="FBJS LiveMessage">LiveMessage FBJS object</a> so your recipient can receive the message.</param>
 /// <param name="message">A JSON-encoded string of the message to send (max length: 1024 bytes).</param>
 public FacebookResponse<Boolean> Send(Int64 recipient, String eventName, String message) {
     System.Collections.Generic.Dictionary<string, object> args = new System.Collections.Generic.Dictionary<string, object>();
     args.Add("recipient", recipient);
     args.Add("event_name", eventName);
     args.Add("message", message);
     var response = this.ExecuteRequest<Boolean>("LiveMessage.send", args);
     return response;
 }
Ejemplo n.º 27
0
 /// <summary>Sets a cookie for a given user and application.</summary>
 /// <param name="uid">The user for whom this cookie needs to be set.</param>
 /// <param name="name">Name of the cookie.</param>
 /// <param name="value">Value of the cookie.</param>
 public FacebookResponse<Boolean> SetCookie(Int64 uid, String name, String value) {
     System.Collections.Generic.Dictionary<string, object> args = new System.Collections.Generic.Dictionary<string, object>();
     args.Add("uid", uid);
     args.Add("name", name);
     args.Add("value", value);
     var response = this.ExecuteRequest<Boolean>("Data.setCookie", args);
     return response;
 }
Ejemplo n.º 28
0
 /// <summary>Updates a user's Facebook status through your application.  This is a streamlined version of <a href="/index.php/Users.setStatus" title="Users.setStatus">users.setStatus</a>.</summary>
 /// <param name="uid">The <a href="/index.php/User_ID" title="User ID">user ID</a> of the user whose status you are setting. 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 ignores this parameter if it is passed by a desktop application.</param>
 /// <param name="status">The status message to set.<br/><b>Note:</b> The maximum message length is 160 characters; messages longer than that limit will be truncated and appended with "...".</param>
 public FacebookResponse<Boolean> Set(Int64 uid, String status) {
     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);
     args.Add("status", status);
     var response = this.ExecuteRequest<Boolean>("Status.set", args);
     return response;
 }
Ejemplo n.º 29
0
 /// <summary>Lets a user post a link on their Wall through your application.</summary>
 /// <param name="uid">The <a href="/index.php/User_ID" title="User ID">user ID</a> of the user posting the link.</param>
 /// <param name="url">The URL for the link.</param>
 /// <param name="comment">The comment the user included with the link.</param>
 public FacebookResponse<Int64> Post(Int64 uid, String url, String comment) {
     System.Collections.Generic.Dictionary<string, object> args = new System.Collections.Generic.Dictionary<string, object>();
     args.Add("uid", uid);
     args.Add("url", url);
     args.Add("comment", comment);
     var response = this.ExecuteRequest<Int64>("Links.post", args);
     return response;
 }
Ejemplo n.º 30
0
        public void ProcessRequest(HttpContext context)
        {
            NFMT.Common.UserModel user = Utility.UserUtility.CurrentUser;

            int pageIndex = 1, pageSize = 10;
            string orderStr = string.Empty, whereStr = string.Empty;

            int status = 0;
            if (!string.IsNullOrEmpty(context.Request.QueryString["s"]))
            {
                if (!int.TryParse(context.Request.QueryString["s"], out status))
                    status = 0;
            }

            int mover = 0;
            if (!string.IsNullOrEmpty(context.Request.QueryString["m"]))
            {
                if (!int.TryParse(context.Request.QueryString["m"], out mover))
                    mover = 0;
            }

            int deliverPlaceId = 0;
            if (!string.IsNullOrEmpty(context.Request.QueryString["d"]))
            {
                if (!int.TryParse(context.Request.QueryString["d"], out deliverPlaceId))
                    deliverPlaceId = 0;
            }

            if (!string.IsNullOrEmpty(context.Request.QueryString["pagenum"]))
                int.TryParse(context.Request.QueryString["pagenum"], out pageIndex);
            pageIndex++;
            if (!string.IsNullOrEmpty(context.Request.QueryString["pagesize"]))
                int.TryParse(context.Request.QueryString["pagesize"], out pageSize);

            if (!string.IsNullOrEmpty(context.Request.QueryString["sortdatafield"]) && !string.IsNullOrEmpty(context.Request.QueryString["sortorder"]))
                orderStr = string.Format("{0} {1}", context.Request.QueryString["sortdatafield"].Trim(), context.Request.QueryString["sortorder"].Trim());

            NFMT.WareHouse.BLL.RepoBLL repoBLL = new NFMT.WareHouse.BLL.RepoBLL();
            NFMT.Common.SelectModel select = repoBLL.GetSelectModel(pageIndex, pageSize, orderStr, status, mover, deliverPlaceId);
            NFMT.Common.ResultModel result = repoBLL.Load(user, select);

            context.Response.ContentType = "application/json; charset=utf-8";
            if (result.ResultStatus != 0)
            {
                context.Response.Write(result.Message);
                context.Response.End();
            }

            System.Data.DataTable dt = result.ReturnValue as System.Data.DataTable;
            System.Collections.Generic.Dictionary<string, object> dic = new System.Collections.Generic.Dictionary<string, object>();

            dic.Add("count", result.AffectCount);
            dic.Add("data", dt);

            string postData = Newtonsoft.Json.JsonConvert.SerializeObject(dic);

            context.Response.Write(postData);
        }
Ejemplo n.º 31
0
        /// <summary>
        /// This is a magic (aka Trust the force) method which goes through the
        /// CLI command arguments and look for a ticker IDs. The emthod recognize
        /// different formats of tickers. For example
        /// - the unique integer 80613003
        /// - partial integer 13003 (if unique)
        /// - description 'Call 1800 Nov'
        /// - description 'C1800Nov'
        /// - description 'Put1800 Nov'
        /// - full name 'TA9Z00960C'
        /// </summary>
        protected bool FindSecurity(string text, out int id)
        {
            id = 0;
            bool res = false;

            // get the list of securities
            int[] ids = marketSimulationMaof.GetSecurities();
            // my key is name of the option and my value is unique option Id (integer)
            // On TASE ID is an integer
            System.Collections.Generic.Dictionary <string, int> names = new System.Collections.Generic.Dictionary <string, int>(ids.Length);
            // i need an array (string) of IDs to look for patial integer IDs
            System.Text.StringBuilder idNames = new System.Text.StringBuilder(ids.Length * 10);
            // fill the dictionary and string of all IDs
            foreach (int i in ids)
            {
                MarketSimulationMaof.Option option = marketSimulationMaof.GetOption(i);
                string name = convertBnoName(option.GetName());
                if (name != null)
                {
                    names.Add(name, i);
                }
                idNames.Append(i); idNames.Append(" ");
            }
            string idNamesStr = idNames.ToString();

            // look in the command for regexp jan|feb)($| +)' first
            // Other possibilities are: ' +([0-9]+) *([c,p]) *(jan|feb)($| +)'
            // the final case is any set of digits ' +([0-9]+)($| +)'
            const string monthPattern   = "JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC";
            const string putcallPattern = "c|p|C|P|call|put|CALL|PUT|Call|Put]";
            const string pattern1       = " +(" + putcallPattern + ") *([0-9]+) *(" + monthPattern + ")($| +)";
            const string pattern2       = " +([0-9]+) *(" + putcallPattern + ") *(" + monthPattern + ")($| +)";
            const string pattern3       = " +([0-9]+)($| +)";

            System.Text.RegularExpressions.GroupCollection groups;
            int matchesCount;

            do
            {
                GetMatchGroups(pattern1, text, out groups, out matchesCount);
                if (matchesCount > 1)
                {
                    System.Console.WriteLine("I expect one and only one match for '" + pattern1 + "' instead of " + matchesCount);
                    break;
                }

                if (matchesCount == 1)
                {
                    string putcall = groups[1].Captures[0].ToString();                     // group[0] is reserved for the whole match
                    string strike  = groups[2].Captures[0].ToString();
                    string month   = groups[3].Captures[0].ToString();
                    res = FindSecurity(names, putcall, strike, month, out id);
                    break;
                }

                GetMatchGroups(pattern2, text, out groups, out matchesCount);
                if (matchesCount > 1)
                {
                    System.Console.WriteLine("I expect one and only one match for '" + pattern2 + "' instead of " + matchesCount);
                    break;
                }
                if (matchesCount == 1)
                {
                    string strike  = groups[2].Captures[0].ToString();                     // group[0] is reserved for the whole match
                    string putcall = groups[1].Captures[0].ToString();
                    string month   = groups[3].Captures[0].ToString();
                    res = FindSecurity(names, putcall, strike, month, out id);
                    break;
                }

                // finally i look just for any sequence of digits
                GetMatchGroups(pattern3, text, out groups, out matchesCount);
                if (matchesCount > 0)
                {
                    string digits      = groups[0].Captures[0].ToString();                // group[0] is reserved for the whole match
                    int    idxFirst    = idNamesStr.IndexOf(digits);                      // idNamesStr is a string containing all existing Ids followed by blank
                    int    idxSecond   = idNamesStr.LastIndexOf(digits);
                    string firstMatch  = idNamesStr.Substring(idxFirst, idNamesStr.IndexOf(" ", idxFirst + 1) - idxFirst);
                    string secondMatch = idNamesStr.Substring(idxSecond, idNamesStr.IndexOf(" ", idxSecond + 1) - idxSecond);
                    if (idxFirst != idxSecond)
                    {
                        System.Console.WriteLine("I have at least two matches '" + firstMatch + "' and '" + secondMatch + "'");
                        break;
                    }
                    // System.Console.WriteLine("firstMatch={0},secondMatch={1},digits={2}",firstMatch,secondMatch,digits);
                    // i got a single match - convert to ID
                    id  = Int32.Parse(firstMatch);
                    res = true;
                    break;
                }

                res = false;
            }while (false);


            return(res);
        }
Ejemplo n.º 32
0
        private System.Collections.Generic.Dictionary <string, SKUItem> GetSkus(ProductInfo product, decimal weight, System.Web.HttpContext context)
        {
            string str = context.Request.Form["SkuString"];

            System.Collections.Generic.Dictionary <string, SKUItem> result;
            if (string.IsNullOrEmpty(str))
            {
                product.HasSKU = false;
                System.Collections.Generic.Dictionary <string, SKUItem> dictionary2 = new System.Collections.Generic.Dictionary <string, SKUItem>();
                SKUItem item = 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
                };
                dictionary2.Add("0", item);
                result = dictionary2;
            }
            else
            {
                product.HasSKU = true;
                System.Collections.Generic.Dictionary <string, SKUItem> dictionary3 = new System.Collections.Generic.Dictionary <string, SKUItem>();
                string[] array = System.Web.HttpUtility.UrlDecode(str).Split(new char[]
                {
                    '|'
                });
                for (int i = 0; i < array.Length; i++)
                {
                    string   str2     = array[i];
                    string[] strArray = str2.Split(new char[]
                    {
                        ','
                    });
                    SKUItem item2 = new SKUItem
                    {
                        SKU       = strArray[0],
                        Weight    = weight,
                        Stock     = int.Parse(strArray[1]),
                        SalePrice = decimal.Parse(strArray[2])
                    };
                    string   str3   = strArray[3];
                    string   str4   = "";
                    string[] array2 = str3.Split(new char[]
                    {
                        ';'
                    });
                    for (int j = 0; j < array2.Length; j++)
                    {
                        string   str5      = array2[j];
                        string[] strArray2 = str5.Split(new char[]
                        {
                            ':'
                        });
                        int specificationId      = ProductTypeHelper.GetSpecificationId(product.TypeId.Value, strArray2[0]);
                        int specificationValueId = ProductTypeHelper.GetSpecificationValueId(specificationId, strArray2[1]);
                        str4 = str4 + specificationValueId + "_";
                        item2.SkuItems.Add(specificationId, specificationValueId);
                    }
                    item2.SkuId = str4.Substring(0, str4.Length - 1);
                    dictionary3.Add(item2.SkuId, item2);
                }
                result = dictionary3;
            }
            return(result);
        }
Ejemplo n.º 33
0
        private void init_Avail_data()
        {
            System.Collections.Generic.Dictionary <long, string> dictionary = new System.Collections.Generic.Dictionary <long, string>();
            if (this.m_groupID >= 0L)
            {
                GroupInfo groupByID  = GroupInfo.GetGroupByID(this.m_groupID);
                string    memberList = groupByID.GetMemberList();
                if (memberList != null && memberList.Length > 0)
                {
                    string[] array = memberList.Split(new string[]
                    {
                        ","
                    }, System.StringSplitOptions.RemoveEmptyEntries);
                    string[] array2 = array;
                    for (int i = 0; i < array2.Length; i++)
                    {
                        string value = array2[i];
                        long   key   = (long)System.Convert.ToInt32(value);
                        dictionary.Add(key, "");
                    }
                }
            }
            this.dgvAvail.DataSource = null;
            this.Avail_tb            = new DataTable();
            this.Avail_tb.Columns.Add("objID", typeof(string));
            this.Avail_tb.PrimaryKey = new DataColumn[]
            {
                this.Avail_tb.Columns[0]
            };
            string groupType;

            if ((groupType = this.m_groupType) != null)
            {
                if (cct == null)
                {
                    cct = new System.Collections.Generic.Dictionary <string, int>(7)
                    {
                        {
                            "zone",
                            0
                        },

                        {
                            "rack",
                            1
                        },

                        {
                            "allrack",
                            2
                        },

                        {
                            "dev",
                            3
                        },

                        {
                            "alldev",
                            4
                        },

                        {
                            "outlet",
                            5
                        },

                        {
                            "alloutlet",
                            6
                        }
                    };
                }
                int num;
                if (cct.TryGetValue(groupType, out num))
                {
                    switch (num)
                    {
                    case 0:
                    {
                        this.Avail_tb.Columns.Add(EcoLanguage.getMsg(LangRes.Group_NMZone, new string[0]), typeof(string));
                        System.Collections.ArrayList   allZone    = ZoneInfo.getAllZone();
                        System.Collections.IEnumerator enumerator = allZone.GetEnumerator();
                        try
                        {
                            while (enumerator.MoveNext())
                            {
                                ZoneInfo zoneInfo = (ZoneInfo)enumerator.Current;
                                string   text     = zoneInfo.ZoneID.ToString();
                                if (!dictionary.ContainsKey(zoneInfo.ZoneID))
                                {
                                    string[] values = new string[]
                                    {
                                        text,
                                        zoneInfo.ZoneName
                                    };
                                    this.Avail_tb.Rows.Add(values);
                                }
                            }
                            return;
                        }
                        finally
                        {
                            System.IDisposable disposable = enumerator as System.IDisposable;
                            if (disposable != null)
                            {
                                disposable.Dispose();
                            }
                        }
                        break;
                    }

                    case 1:
                    case 2:
                        break;

                    case 3:
                    case 4:
                        goto IL_401;

                    case 5:
                    case 6:
                        goto IL_50F;

                    default:
                        return;
                    }
                    this.Avail_tb.Columns.Add(EcoLanguage.getMsg(LangRes.Group_NMRack, new string[0]), typeof(string));
                    this.Avail_tb.Columns.Add(EcoLanguage.getMsg(LangRes.Group_NMZone, new string[0]), typeof(string));
                    System.Collections.ArrayList   allZone2        = ZoneInfo.getAllZone();
                    System.Collections.ArrayList   allRack_NoEmpty = RackInfo.GetAllRack_NoEmpty();
                    System.Collections.IEnumerator enumerator2     = allRack_NoEmpty.GetEnumerator();
                    try
                    {
                        while (enumerator2.MoveNext())
                        {
                            RackInfo rackInfo = (RackInfo)enumerator2.Current;
                            if (!dictionary.ContainsKey(rackInfo.RackID))
                            {
                                string displayRackName = rackInfo.GetDisplayRackName(EcoGlobalVar.RackFullNameFlag);
                                string text2           = rackInfo.RackID.ToString();
                                bool   flag            = false;
                                string text3           = "";
                                foreach (ZoneInfo zoneInfo2 in allZone2)
                                {
                                    text3 = zoneInfo2.ZoneName;
                                    string[] source = zoneInfo2.RackInfo.Split(new char[]
                                    {
                                        ','
                                    });
                                    if (source.Contains(text2))
                                    {
                                        flag = true;
                                        break;
                                    }
                                }
                                string[] values;
                                if (flag)
                                {
                                    values = new string[]
                                    {
                                        text2,
                                        displayRackName,
                                        text3
                                    };
                                }
                                else
                                {
                                    values = new string[]
                                    {
                                        text2,
                                        displayRackName,
                                        ""
                                    };
                                }
                                this.Avail_tb.Rows.Add(values);
                            }
                        }
                        return;
                    }
                    finally
                    {
                        System.IDisposable disposable3 = enumerator2 as System.IDisposable;
                        if (disposable3 != null)
                        {
                            disposable3.Dispose();
                        }
                    }
IL_401:
                    this.Avail_tb.Columns.Add(EcoLanguage.getMsg(LangRes.Group_NMDev, new string[0]), typeof(string));
                    this.Avail_tb.Columns.Add(EcoLanguage.getMsg(LangRes.Group_NMRack, new string[0]), typeof(string));
                    System.Collections.Generic.List <DeviceInfo> allDevice = DeviceOperation.GetAllDevice();
                    using (System.Collections.Generic.List <DeviceInfo> .Enumerator enumerator4 = allDevice.GetEnumerator())
                    {
                        while (enumerator4.MoveNext())
                        {
                            DeviceInfo current = enumerator4.Current;
                            if (!dictionary.ContainsKey((long)current.DeviceID))
                            {
                                string   deviceName       = current.DeviceName;
                                string   text4            = current.DeviceID.ToString();
                                RackInfo rackByID         = RackInfo.getRackByID(current.RackID);
                                string   displayRackName2 = rackByID.GetDisplayRackName(EcoGlobalVar.RackFullNameFlag);
                                string[] values           = new string[]
                                {
                                    text4,
                                    deviceName,
                                    displayRackName2
                                };
                                this.Avail_tb.Rows.Add(values);
                            }
                        }
                        return;
                    }
IL_50F:
                    this.Avail_tb.Columns.Add(EcoLanguage.getMsg(LangRes.Group_NMOutlet, new string[0]), typeof(string));
                    this.Avail_tb.Columns.Add(EcoLanguage.getMsg(LangRes.Group_NMDev, new string[0]), typeof(string));
                    allDevice = DeviceOperation.GetAllDevice();
                    foreach (DeviceInfo current2 in allDevice)
                    {
                        System.Collections.Generic.List <PortInfo> portInfo = current2.GetPortInfo();
                        foreach (PortInfo current3 in portInfo)
                        {
                            if (!dictionary.ContainsKey((long)current3.ID))
                            {
                                string[] values = new string[]
                                {
                                    current3.ID.ToString(),
                                          current3.PortName,
                                          current2.DeviceName
                                };
                                this.Avail_tb.Rows.Add(values);
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 34
0
 protected void btnSend_Click(object sender, System.EventArgs e)
 {
     System.Collections.Generic.IList <string>              userList   = this.GetUserList();
     System.Collections.Generic.IEnumerable <string>        enumerable = userList.Distinct <string>();
     System.Collections.Generic.Dictionary <string, string> dictionary = new System.Collections.Generic.Dictionary <string, string>();
     if (enumerable.Count <string>() > 0)
     {
         System.Collections.Generic.List <Mail> list = new System.Collections.Generic.List <Mail>();
         string value = string.Empty;
         int    num   = 0;
         foreach (string current in enumerable)
         {
             value = System.Guid.NewGuid().ToString();
             dictionary.Add(current, value);
             string toMailId = System.Guid.NewGuid().ToString();
             list.Add(new Mail
             {
                 MailId        = value,
                 ToMailId      = toMailId,
                 MailName      = this.txtName.Text.Trim(),
                 MailFrom      = base.UserCode,
                 MailTo        = current,
                 AllMailToCode = this.hfldTo.Value,
                 AllMailTo     = this.txtTo.Text,
                 AllCopytoCode = this.hfldCopyto.Value,
                 AllCopyto     = this.txtCopyto.Text,
                 MailContent   = this.txtContent.Value,
                 IsValid       = true,
                 IsReaded      = false,
                 MailType      = "I",
                 AnnexId       = (string)this.ViewState["annexId"],
                 InputDate     = System.DateTime.Now.AddSeconds((double)num)
             });
             list.Add(new Mail
             {
                 MailId        = System.Guid.NewGuid().ToString(),
                 ToMailId      = toMailId,
                 MailName      = this.txtName.Text.Trim(),
                 MailFrom      = base.UserCode,
                 MailTo        = current,
                 AllMailToCode = this.hfldTo.Value,
                 AllMailTo     = this.txtTo.Text,
                 AllCopytoCode = this.hfldCopyto.Value,
                 AllCopyto     = this.txtCopyto.Text,
                 MailContent   = this.txtContent.Value,
                 IsValid       = true,
                 IsReaded      = false,
                 MailType      = "O",
                 AnnexId       = (string)this.ViewState["annexId"],
                 InputDate     = System.DateTime.Now.AddSeconds((double)num)
             });
             num++;
         }
         if (!string.IsNullOrEmpty(this.mailId) && this.edit == "1")
         {
             this.mailService.Delete(this.mailId);
         }
         this.mailService.AddOrUpdate(list);
         if (this.chkMobileMsg.Checked)
         {
             this.SendMobileMsg();
         }
         if (this.chkDbsj.Checked)
         {
             this.SendDbsj(dictionary);
         }
         this.hfldMailId.Value = value;
         base.RegisterScript("selectSend();");
         return;
     }
     base.RegisterScript("alert('收件人不能为空!');");
 }
Ejemplo n.º 35
0
        private System.Collections.Generic.Dictionary <string, SKUItem> GetSkus(ProductInfo product, int 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"]),
                            PurchasePrice = 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];
                    sKUItem.Weight        = weight;
                    sKUItem.Stock         = int.Parse(array2[1]);
                    sKUItem.PurchasePrice = (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]);
                        text4 = text4 + specificationValueId + "_";
                        sKUItem.SkuItems.Add(specificationId, specificationValueId);
                    }
                    sKUItem.SkuId = text4.Substring(0, text4.Length - 1);
                    dictionary.Add(sKUItem.SkuId, sKUItem);
                }
            }
            return(dictionary);
        }
Ejemplo n.º 36
0
        private void button3_Click(object sender, EventArgs e)
        {
            //Excell
            HSSFWorkbook   hssfwb;
            OpenFileDialog ofd;
            ISheet         sheet0 = null;
            ISheet         sheet1 = null;
            ISheet         sheet2 = null;
            ISheet         sheet3 = null;
            ISheet         sheet4 = null;
            ISheet         sheet5 = null;

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

            ofd        = new OpenFileDialog();
            ofd.Filter = "Excell table Microsoft Office 1998-2003 (*.xls)|*.xls";
            Stream myStream = null;

            processPb.Value = 0;
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                int IdQ = 0;
                try
                {
                    DateTime localDate = DateTime.Now;

                    filesPath.Add(0, ofd.FileName); // Добавление файлового пути
                    using (FileStream file = new FileStream(ofd.FileName, FileMode.Open, FileAccess.Read))
                    {
                        hssfwb = new HSSFWorkbook(file);
                    }
                    bool EROR = true;
                    // Получение листов из Excell
                    sheet0            = hssfwb.GetSheetAt(0);
                    sheet1            = hssfwb.GetSheetAt(1);
                    sheet2            = hssfwb.GetSheetAt(2);
                    sheet3            = hssfwb.GetSheetAt(3);
                    sheet4            = hssfwb.GetSheetAt(4);
                    sheet5            = hssfwb.GetSheetAt(5);
                    processPb.Maximum = sheet0.LastRowNum + 5;

                    string connectionString;
                    connectionString = "SERVER=" + server + ";" + "DATABASE=" +
                                       database + ";" +
                                       "port=" + port + ";" + "UID=" + uid + ";" + "PASSWORD="******";charset=utf8;";
                    connection1 = new MySqlConnection(connectionString);
                    connection1.Open();
                    MySqlCommand command = new MySqlCommand("INSERT INTO Qualification (Qualification_EN, Qualification_UA, Degree,Date," +
                                                            " FieldStudy_UA, FieldStudy_EN, FirstSpecialty_UA, FirstSpecialty_EN, SecondSpecialty_UA, SecondSpecialty_EN, Specialization_UA, Specialization_EN)" +
                                                            " VALUES (@Qualification_EN, @Qualification_UA,@Degree,@Date,@FieldStudy_UA, @FieldStudy_EN, @FirstSpecialty_UA, @FirstSpecialty_EN," +
                                                            " @SecondSpecialty_UA, @SecondSpecialty_EN, @Specialization_UA, @Specialization_EN)", connection1);
                    command.Parameters.AddWithValue("Qualification_EN", sheet1.GetRow(1).GetCell(1).StringCellValue);
                    command.Parameters.AddWithValue("Qualification_UA", sheet1.GetRow(0).GetCell(1).StringCellValue);
                    command.Parameters.AddWithValue("FieldStudy_UA", sheet1.GetRow(2).GetCell(1).StringCellValue);
                    command.Parameters.AddWithValue("FieldStudy_EN", sheet1.GetRow(3).GetCell(1).StringCellValue);
                    try { command.Parameters.AddWithValue("FirstSpecialty_UA", sheet1.GetRow(4).GetCell(1).StringCellValue); }
                    catch { command.Parameters.AddWithValue("FirstSpecialty_UA", ""); }
                    try { command.Parameters.AddWithValue("FirstSpecialty_EN", sheet1.GetRow(5).GetCell(1).StringCellValue); }
                    catch { command.Parameters.AddWithValue("FirstSpecialty_EN", ""); }
                    try { command.Parameters.AddWithValue("SecondSpecialty_UA", sheet1.GetRow(6).GetCell(1).StringCellValue); }
                    catch { command.Parameters.AddWithValue("SecondSpecialty_UA", ""); }
                    try { command.Parameters.AddWithValue("SecondSpecialty_EN", sheet1.GetRow(7).GetCell(1).StringCellValue); }
                    catch { command.Parameters.AddWithValue("SecondSpecialty_EN", ""); }
                    try { command.Parameters.AddWithValue("Specialization_UA", sheet1.GetRow(8).GetCell(1).StringCellValue); }
                    catch { command.Parameters.AddWithValue("Specialization_UA", ""); }
                    try { command.Parameters.AddWithValue("Specialization_EN", sheet1.GetRow(9).GetCell(1).StringCellValue); }
                    catch { command.Parameters.AddWithValue("Specialization_EN", ""); }
                    command.Parameters.AddWithValue("Degree", sheet1.GetRow(10).GetCell(1).StringCellValue);
                    command.Parameters.AddWithValue("Date", DateTime.Now);
                    command.ExecuteNonQuery();

                    string ComandSQL2 = "SELECT qualification.Qualification_ID FROM qualification ORDER BY" +
                                        " qualification.Qualification_ID DESC LIMIT 1";
                    command = new MySqlCommand(ComandSQL2, connection1);
                    MySqlDataReader reader2 = command.ExecuteReader();
                    reader2.Read();
                    IdQ              = reader2.GetInt32(0);
                    processPb.Value += 1;
                    reader2.Close();

                    string upDate = "UPDATE `National_framework` SET Level_qualification_UA=@Level_qualification_UA," +
                                    "`Level_qualification_EN`=@Level_qualification_EN," +
                                    "`Official_duration_programme_UA`=@Official_duration_programme_UA," +
                                    "`Official_duration_programme_EN`=@Official_duration_programme_EN," +
                                    "`Access_requirements_UA`=@Access_requirements_UA" +
                                    ",`Access_requirements_EN`=@Access_requirements_EN " +
                                    ",`Access_further_study_UA`=@Access_further_study_UA," +
                                    "`Access_further_study_EN`=@Access_further_study_EN," +
                                    "`Professional_status_UA`=@Professional_status_UA," +
                                    "`Professional_status_EN`=@Professional_status_EN" +
                                    "  WHERE National_framework.Qualification_ID=@Qualification_ID";
                    command = new MySqlCommand(upDate, connection1);

                    command.Parameters.AddWithValue("Qualification_ID", IdQ.ToString());
                    command.Parameters.AddWithValue("Level_qualification_UA", sheet2.GetRow(0).GetCell(1).StringCellValue);
                    command.Parameters.AddWithValue("Level_qualification_EN", sheet2.GetRow(1).GetCell(1).StringCellValue);
                    command.Parameters.AddWithValue("Official_duration_programme_UA", sheet2.GetRow(2).GetCell(1).StringCellValue);
                    command.Parameters.AddWithValue("Official_duration_programme_EN", sheet2.GetRow(3).GetCell(1).StringCellValue);
                    command.Parameters.AddWithValue("Access_requirements_UA", sheet2.GetRow(4).GetCell(1).StringCellValue);
                    command.Parameters.AddWithValue("Access_requirements_EN", sheet2.GetRow(5).GetCell(1).StringCellValue);
                    command.Parameters.AddWithValue("Access_further_study_UA", sheet2.GetRow(6).GetCell(1).StringCellValue);
                    command.Parameters.AddWithValue("Access_further_study_EN", sheet2.GetRow(7).GetCell(1).StringCellValue);
                    command.Parameters.AddWithValue("Professional_status_UA", sheet2.GetRow(8).GetCell(1).StringCellValue);
                    command.Parameters.AddWithValue("Professional_status_EN", sheet2.GetRow(9).GetCell(1).StringCellValue);

                    command.ExecuteNonQuery();
                    processPb.Value += 1;

                    StringMultiLanguage programSpecification   = new StringMultiLanguage();
                    StringMultiLanguage knowledgeUnderstanding = new StringMultiLanguage();
                    StringMultiLanguage applyingKnowledge      = new StringMultiLanguage();
                    StringMultiLanguage MakingJudgments        = new StringMultiLanguage();
                    for (int row = 1; row < sheet3.LastRowNum; row++)
                    {
                        if (sheet3.GetRow(row).GetCell(1) != null)
                        {
                            if (!string.IsNullOrEmpty(sheet3.GetRow(row).GetCell(1).StringCellValue))
                            {
                                programSpecification.UA = programSpecification.UA + (sheet3.GetRow(row).GetCell(1).StringCellValue + ";_");
                                programSpecification.EN = programSpecification.EN + (sheet3.GetRow(row).GetCell(2).StringCellValue + ";_");
                            }
                        }


                        if (sheet3.GetRow(row).GetCell(3) != null)
                        {
                            if (!string.IsNullOrEmpty(sheet3.GetRow(row).GetCell(3).StringCellValue))
                            {
                                knowledgeUnderstanding.UA = knowledgeUnderstanding.UA + (sheet3.GetRow(row).GetCell(3).StringCellValue + ";_");
                                knowledgeUnderstanding.EN = knowledgeUnderstanding.EN + (sheet3.GetRow(row).GetCell(4).StringCellValue + ";_");
                            }
                        }
                        if (sheet3.GetRow(row).GetCell(5) != null)
                        {
                            if (!string.IsNullOrEmpty(sheet3.GetRow(row).GetCell(5).StringCellValue))
                            {
                                applyingKnowledge.UA = applyingKnowledge.UA + (sheet3.GetRow(row).GetCell(5).StringCellValue + ";_");
                                applyingKnowledge.EN = applyingKnowledge.EN + (sheet3.GetRow(row).GetCell(6).StringCellValue + ";_");
                            }
                        }

                        if (sheet3.GetRow(row).GetCell(7) != null)
                        {
                            if (!string.IsNullOrEmpty(sheet3.GetRow(row).GetCell(7).StringCellValue))
                            {
                                MakingJudgments.UA = MakingJudgments.UA + (sheet3.GetRow(row).GetCell(7).StringCellValue + ";_");
                                MakingJudgments.EN = MakingJudgments.EN + (sheet3.GetRow(row).GetCell(8).StringCellValue + ";_");
                            }
                        }
                    }
                    processPb.Value += 1;

                    upDate = "UPDATE `contents_and_results` SET Form_study_UA=@Form_study_UA," +
                             "`Form_study_EN`=@Form_study_EN," +
                             "`Program_Specification_UA`=@Program_Specification_UA," +
                             "`Program_Specification_EN`=@Program_Specification_EN," +
                             "`Knowledge_undestanding_UA`=@Knowledge_undestanding_UA" +
                             ",`Knowledge_undestanding_EN`=@Knowledge_undestanding_EN " +
                             ",`Application_knowledge_understanding_UA`=@Application_knowledge_understanding_UA," +
                             "`Application_knowledge_understanding_EN`=@Application_knowledge_understanding_EN," +
                             "`Making_judgments_UA`=@Making_judgments_UA," +
                             "`Making_judgments_EN`=@Making_judgments_EN" +
                             "  WHERE contents_and_results.Qualification_ID=@Qualification_ID";
                    command = new MySqlCommand(upDate, connection1);

                    string Form_study = sheet3.GetRow(1).GetCell(0).StringCellValue;



                    // int last = Form_study. ;

                    command.Parameters.AddWithValue("Qualification_ID", IdQ.ToString());
                    command.Parameters.AddWithValue("Form_study_UA", Form_study.Substring(0, Form_study.IndexOf('/')));
                    command.Parameters.AddWithValue("Form_study_EN", Form_study.Substring((Form_study.IndexOf('/') + 1), (Form_study.Length - Form_study.IndexOf('/') - 1)));
                    command.Parameters.AddWithValue("Program_Specification_EN", programSpecification.EN.Replace(";_", "; "));
                    command.Parameters.AddWithValue("Program_Specification_UA", programSpecification.UA.Replace(";_", "; "));
                    command.Parameters.AddWithValue("Knowledge_undestanding_UA", knowledgeUnderstanding.UA.Replace(";_", "; "));
                    command.Parameters.AddWithValue("Knowledge_undestanding_EN", knowledgeUnderstanding.EN.Replace(";_", "; "));
                    command.Parameters.AddWithValue("Application_knowledge_understanding_UA", applyingKnowledge.UA.Replace(";_", "; "));
                    command.Parameters.AddWithValue("Application_knowledge_understanding_EN", applyingKnowledge.EN.Replace(";_", "; "));
                    command.Parameters.AddWithValue("Making_judgments_UA", MakingJudgments.UA.Replace(";_", "; "));
                    command.Parameters.AddWithValue("Making_judgments_EN", MakingJudgments.EN.Replace(";_", "; "));

                    command.ExecuteNonQuery();
                    processPb.Value += 1;
                    /////////////////////////

                    Dictionary <int, int> countries = new Dictionary <int, int>();
                    string ComandSQ = "SELECT MAX(discipline.Discipline_ID) AS expr1 FROM discipline " +
                                      "WHERE discipline.Qualification_ID =" + IdQ.ToString();
                    upDate = "INSERT INTO Discipline (Qualification_ID, Course_title_UA, Course_title_EN, Loans, Hours, Teaching, Differential)" +
                             " VALUES (@Qualification_ID, @Course_title_UA, @Course_title_EN, @Loans, @Hours, @Teaching, @Differential)";

                    for (int row = 1; row <= sheet5.LastRowNum; row++)
                    {
                        try
                        {
                            if (sheet5.GetRow(row) != null) //null is when the row only contains empty cells
                            {
                                command = new MySqlCommand(upDate, connection1);
                                // Создание обьекта студент
                                command.Parameters.AddWithValue("Qualification_ID", IdQ.ToString());
                                command.Parameters.AddWithValue("Course_title_UA", sheet5.GetRow(row).GetCell(0).StringCellValue);
                                command.Parameters.AddWithValue("Course_title_EN", sheet5.GetRow(row).GetCell(1).StringCellValue);
                                command.Parameters.AddWithValue("Loans", (sheet5.GetRow(row).GetCell(2).NumericCellValue));
                                command.Parameters.AddWithValue("Hours", (sheet5.GetRow(row).GetCell(3).NumericCellValue));
                                command.Parameters.AddWithValue("Teaching", sheet5.GetRow(row).GetCell(4).NumericCellValue);
                                command.Parameters.AddWithValue("Differential", (sheet5.GetRow(row).GetCell(5).NumericCellValue == 0) ? "Оцінка" : "Зарах");

                                command.ExecuteNonQuery();


                                command = new MySqlCommand(ComandSQ, connection1);
                                MySqlDataReader reader3 = command.ExecuteReader();
                                reader3.Read();
                                countries.Add(row, reader3.GetInt32(0));
                                reader3.Close();
                                //rbStatus.Text += sheet5.GetRow(row).GetCell(0).StringCellValue + '\n';
                            }
                        }
                        catch {}
                    }

                    processPb.Value += 1;
                    studentFunc(hssfwb, countries, connection1, IdQ);

                    connection1.Close();
                    //processPb.Value += 1;
                    SEARCH Search = new SEARCH();
                    Search.ID = IdQ;
                    Search.StringConnection = connectionString;
                    Search.NewOrOld         = false;
                    this.Visible            = false;
                    Search.ShowDialog();
                    this.Visible = true;
                }
                catch (Exception exc)
                {
                    try
                    {
                        MessageBox.Show(exc.ToString());
                        SEARCH Search = new SEARCH();
                        Search.ID = IdQ;
                        Search.StringConnection = connectionString;
                        Search.NewOrOld         = true;
                        this.Visible            = false;
                        Search.ShowDialog();
                    }
                    catch (Exception exce) { MessageBox.Show(exce.ToString()); }
                }
            }
        }
        public void PackagePublisherPackageFolderMustRespectHierarchy()
        {
            const string ProjectName1 = "PackageTest03";

            string IntegrationFolder = System.IO.Path.Combine("scenarioTests", ProjectName1);
            string CCNetConfigFile   = System.IO.Path.Combine("IntegrationScenarios", "PackagePublisherTest03" + (Platform.IsWindows ? "" : "_linux") + ".xml");
            string ProjectStateFile  = new System.IO.FileInfo(ProjectName1 + ".state").FullName;

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

            string workingDirectory = "Packaging03";

            string infoFolder    = string.Format("{0}{1}some{1}directories{1}deeper{1}_PublishedWebsites{1}MyProject{1}", workingDirectory, System.IO.Path.DirectorySeparatorChar);
            string subInfoFolder = string.Format("{0}{1}AFolder{1}", infoFolder, System.IO.Path.DirectorySeparatorChar);
            string f1            = string.Format("{0}{1}a.txt", infoFolder, System.IO.Path.DirectorySeparatorChar);
            string f2            = string.Format("{0}{1}b.txt", subInfoFolder, System.IO.Path.DirectorySeparatorChar);


            var ios = new CCNet.Core.Util.IoService();

            ios.DeleteIncludingReadOnlyObjects(infoFolder);
            ios.DeleteIncludingReadOnlyObjects("TheMegaWebSite");


            System.IO.Directory.CreateDirectory(infoFolder);
            System.IO.Directory.CreateDirectory(subInfoFolder);


            System.IO.File.WriteAllText(f1, "somedata");
            System.IO.File.WriteAllText(f2, "somedata");

            IntegrationCompleted.Add(ProjectName1, false);

            Log("Clear existing state file, to simulate first run : " + ProjectStateFile);
            System.IO.File.Delete(ProjectStateFile);

            Log("Clear integration folder to simulate first run");
            if (System.IO.Directory.Exists(IntegrationFolder))
            {
                System.IO.Directory.Delete(IntegrationFolder, true);
            }


            CCNet.Remote.Messages.ProjectStatusResponse psr;
            CCNet.Remote.Messages.ProjectRequest        pr1 = new CCNet.Remote.Messages.ProjectRequest(null, ProjectName1);


            Log("Making CruiseServerFactory");
            CCNet.Core.CruiseServerFactory csf = new CCNet.Core.CruiseServerFactory();

            Log("Making cruiseServer with config from :" + CCNetConfigFile);
            using (var cruiseServer = csf.Create(true, CCNetConfigFile))
            {
                // subscribe to integration complete to be able to wait for completion of a build
                cruiseServer.IntegrationCompleted += new EventHandler <ThoughtWorks.CruiseControl.Remote.Events.IntegrationCompletedEventArgs>(CruiseServerIntegrationCompleted);

                Log("Starting cruiseServer");
                cruiseServer.Start();

                System.Threading.Thread.Sleep(250); // give time to start

                Log("Forcing build");
                CheckResponse(cruiseServer.ForceBuild(pr1));

                System.Threading.Thread.Sleep(250); // give time to start the build

                Log("Waiting for integration to complete");
                while (!IntegrationCompleted[ProjectName1])
                {
                    for (int i = 1; i <= 4; i++)
                    {
                        System.Threading.Thread.Sleep(250);
                    }
                    Log(" waiting ...");
                }

                // un-subscribe to integration complete
                cruiseServer.IntegrationCompleted -= new EventHandler <ThoughtWorks.CruiseControl.Remote.Events.IntegrationCompletedEventArgs>(CruiseServerIntegrationCompleted);

                Log("getting project status");
                psr = cruiseServer.GetProjectStatus(pr1);
                CheckResponse(psr);

                Log("Stopping cruiseServer");
                cruiseServer.Stop();

                Log("waiting for cruiseServer to stop");
                cruiseServer.WaitForExit(pr1);
                Log("cruiseServer stopped");
            }

            Log("Checking the data");
            string ExpectedZipFile = string.Format("{0}{1}Artifacts{1}1{1}Project-package.zip", ProjectName1, System.IO.Path.DirectorySeparatorChar);

            Assert.IsTrue(System.IO.File.Exists(ExpectedZipFile), "zip package not found at expected location");

            ICSharpCode.SharpZipLib.Zip.ZipFile zf = new ICSharpCode.SharpZipLib.Zip.ZipFile(ExpectedZipFile);
            string expectedFiles = string.Empty;

            foreach (ICSharpCode.SharpZipLib.Zip.ZipEntry ze in zf)
            {
                System.Diagnostics.Debug.WriteLine(ze.Name);
                expectedFiles += ze.Name;
            }

            Assert.AreEqual(@"MegaWebSite/AFolder/b.txtMegaWebSite/a.txt", expectedFiles);
        }
Ejemplo n.º 38
0
        protected void Button2_Click(object sender, EventArgs e)
        {
            //            Response.Clear();
            //            Response.ContentType = "application/vnd.ms-excel";
            //            Response.Charset = "GB2312";
            //            Response.AppendHeader("Content-Disposition", "attachment;filename=" + xlfile);
            //            Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");  //设置输出流为简体中文
            //            this.EnableViewState = false;
            //            Response.Write("<meta http-equiv=Content-Type content=\"text/html; charset=GB2312\">");
            //            Response.Write("<?xml version='1.0'?><?mso-application progid='Excel.Sheet'?>");
            //            Response.Write(@"<Workbook xmlns='urn:schemas-microsoft-com:office:spreadsheet'
            //      xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:x='urn:schemas-microsoft-com:office:excel'
            //      xmlns:ss='urn:schemas-microsoft-com:office:spreadsheet' xmlns:html='http://www.w3.org/TR/REC-html40'>");
            //            System.IO.StringWriter sw = new System.IO.StringWriter();
            //            System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw);
            //            show();
            //            for (int i = 0; i < 10; i++)
            //            {
            //                Response.Write("<Worksheet ss:Name='Sheet" + (i + 1) + "'>");
            //                Panel2.RenderControl(hw);
            //                Panel1.RenderControl(hw);
            //                Response.Write(sw.ToString());
            //                Response.Write("</Worksheet>");
            //                Response.Flush();
            //            }
            //            Response.Write("</Workbook>");
            //            Response.End();


            //Response.Clear();
            Response.ClearContent();
            Response.BufferOutput = true;
            Response.Charset      = "utf-8";
            Response.ContentType  = "application/ms-excel";
            Response.AddHeader("Content-Transfer-Encoding", "binary");
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            //Response.AppendHeader("Content-Disposition", "attachment;filename="+Server.UrlEncode("孟宪会Excel表格测试")+".xls");
            // 采用下面的格式,将兼容 Excel 2003,Excel 2007, Excel 2010。
            this.EnableViewState = false;
            String FileName = "销售结算明细表";

            if (!String.IsNullOrEmpty(Request.UserAgent))
            {
                // firefox 里面文件名无需编码。
                if (!(Request.UserAgent.IndexOf("Firefox") > -1 && Request.UserAgent.IndexOf("Gecko") > -1))
                {
                    FileName = Server.UrlEncode(FileName);
                }
            }
            Response.AppendHeader("Content-Disposition", "attachment;filename=" + FileName + ".xls");

            Response.Write("<?xml version='1.0'?><?mso-application progid='Excel.Sheet'?>");
            //Response.Write("<meta http-equiv=Content-Type content=\"text/html; charset=GB2312\">");
            Response.Write(@"<Workbook xmlns='urn:schemas-microsoft-com:office:spreadsheet'  
      xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:x='urn:schemas-microsoft-com:office:excel'  
      xmlns:ss='urn:schemas-microsoft-com:office:spreadsheet' xmlns:html='http://www.w3.org/TR/REC-html40'>");

            Response.Write(@"<Styles><Style ss:ID='Default' ss:Name='Normal'><Alignment ss:Vertical='Center'/>  
      <Borders/><Font ss:FontName='宋体' x:CharSet='134' ss:Size='12'/><Interior/><NumberFormat/><Protection/></Style>");
            //定义标题样式
            Response.Write(@"<Style ss:ID='Header'><Borders><Border ss:Position='Bottom' ss:LineStyle='Continuous' ss:Weight='1'/>  
       <Border ss:Position='Left' ss:LineStyle='Continuous' ss:Weight='1'/>  
       <Border ss:Position='Right' ss:LineStyle='Continuous' ss:Weight='1'/>  
       <Border ss:Position='Top' ss:LineStyle='Continuous' ss:Weight='1'/></Borders>  
       <Font ss:FontName='宋体' x:CharSet='134' ss:Size='18' ss:Color='#FF0000' ss:Bold='1'/></Style>");

            //定义边框
            Response.Write(@"<Style ss:ID='border'><NumberFormat ss:Format='@'/><Borders>  
      <Border ss:Position='Bottom' ss:LineStyle='Continuous' ss:Weight='1'/>  
      <Border ss:Position='Left' ss:LineStyle='Continuous' ss:Weight='1'/>  
      <Border ss:Position='Right' ss:LineStyle='Continuous' ss:Weight='1'/>  
      <Border ss:Position='Top' ss:LineStyle='Continuous' ss:Weight='1'/></Borders></Style>");


            Response.Write(@"<Style ss:ID='s82'><Borders>
    <Border ss:Position='Bottom' ss:LineStyle='Continuous' ss:Weight='1'/>
    <Border ss:Position='Left' ss:LineStyle='Continuous' ss:Weight='1'/>
    <Border ss:Position='Right' ss:LineStyle='Continuous' ss:Weight='1'/>
    <Border ss:Position='Top' ss:LineStyle='Continuous' ss:Weight='1'/>
   </Borders><Font ss:FontName='宋体' x:CharSet='134' ss:Size='12' ss:Color='#FFFFFF'/>
   <Interior ss:Color='#366092' ss:Pattern='Solid'/>
   <NumberFormat ss:Format='@'/></Style>");

            Response.Write("</Styles>");



            //System.IO.StringWriter sw = new System.IO.StringWriter();
            //System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw);
            show();

            foreach (var u in user)
            {
                int sumCount = all_propertyList.Count + 6;
                if (sumCount % 2 == 0)
                {
                    sumCount = sumCount / 2;
                }
                else
                {
                    sumCount = sumCount / 2;
                }
                Response.Write("<Worksheet ss:Name='" + u.LoginName + "'>");


                Response.Write(@"<Table x:FullColumns='1' x:FullRows='1' ss:DefaultColumnWidth='73'>");
                string report1_String = "<Row ss:AutoFitHeight='1' ss:style='height: 20px; background-color: #336699; color: White;'>";

                Response.Write(string.Format("<Row ss:AutoFitHeight='1' ss:style='height: 20px; background-color: #336699; color: White;'>"));
                Response.Write(string.Format("<Cell ss:StyleID='s82' ss:MergeAcross='{4}'  ><Data ss:Type='String'>公司名称:{0}     财年年月:{1} 公司年度总销售额:{2}     公司年度总用车里程数:{3}</Data></Cell>",
                                             lblSimpName1.Text, lblYearMonth.Text, lblSellTotal.Text, lblCarTotal.Text, (sumCount - 1)));
                Response.Write("</Row>");

                //body
                Response.Write(string.Format("<Row ss:AutoFitHeight='1'>"));

                GetHtml_S82("费用类型");

                for (int i = 0; i < all_propertyList.Count; i++)
                {
                    if (i < sumCount - 1)
                    {
                        GetHtml_S82(all_propertyList[i].CostType);
                    }
                    else
                    {
                        report1_String += GetHtml_S82_String(all_propertyList[i].CostType);
                    }
                }

                report1_String += GetHtml_S82_String("总计");
                report1_String += GetHtml_S82_String("用车公里数");
                report1_String += GetHtml_S82_String("用车百分比");
                report1_String += GetHtml_S82_String("总销售额");
                report1_String += GetHtml_S82_String("销售额百分比");
                report1_String += "</Row>";
                Response.Write("</Row>");

                //具体数据
                decimal sum_AllTotal = 0;
                decimal sum_RoadLong = 0;
                System.Collections.Generic.Dictionary <int, decimal> tsTbComm = new System.Collections.Generic.Dictionary <int, decimal>();
                System.Collections.Generic.Dictionary <int, decimal> tsTbSpec = new System.Collections.Generic.Dictionary <int, decimal>();

                decimal RoadLong = 0;
                var     carM     = UseCarDetailList.Find(t => t.UserId == u.Id);
                if (carM != null)
                {
                    RoadLong = carM.RoadLong;
                }
                decimal sellT = 0;
                var     sellM = reportDetailList.Find(t => t.AE == u.LoginName);
                if (sellM != null)
                {
                    sellT = sellM.SellTotal;
                }
                string baifenbi = "0%";

                //所有费用汇总
                decimal allTotal = 0;
                var     user_spec_propertyList = spec_propertyList.FindAll(uu => uu.UserID == u.Id);


                if (RoadLongTotal == 0 && SellTotal == 0 && user_spec_propertyList.Sum(t => t.Total) == 0)
                {
                    continue;
                }
                Response.Write(string.Format("<Row ss:AutoFitHeight='1'>"));
                report1_String += "<Row ss:AutoFitHeight='1'>";
                GetHtml(u.LoginName);

                int index = 0;
                foreach (var m in all_propertyList)
                {
                    if (m.MyProperty == "公共")
                    {
                        decimal m_value = 0;
                        var     com_m   = comm_propertyList.Find(t => t.CostTypeId == m.Id && t.CompId == u.CompanyId);

                        if (com_m != null)
                        {
                            if (m.CostType == "汽油费补差" || m.CostType == "汽车维修费" || m.CostType == "汽车保险")
                            {
                                if (RoadLongTotal != 0)
                                {
                                    m_value = (RoadLong / RoadLongTotal) * com_m.Total;
                                }
                            }
                            else
                            {
                                if (SellTotal != 0)
                                {
                                    m_value  = (sellT / SellTotal) * com_m.Total;
                                    baifenbi = ((sellT / SellTotal) * 100).ToString("n2") + "%";
                                }
                            }
                        }
                        if (!tsTbComm.ContainsKey(m.Id))
                        {
                            tsTbComm.Add(m.Id, m_value);
                        }
                        else
                        {
                            tsTbComm[m.Id] = tsTbComm[m.Id] + m_value;
                        }
                        allTotal += m_value;

                        if (index < sumCount - 1)
                        {
                            GetNumber(m_value.ToString("n2"));
                        }
                        else
                        {
                            report1_String += GetNumber_String(m_value.ToString("n2"));
                        }
                    }
                    if (m.MyProperty == "个性")
                    {
                        decimal m_value = 0;
                        var     spec_m  = user_spec_propertyList.Find(t => t.CostTypeId == m.Id && t.CompId == u.CompanyId);
                        if (spec_m != null)
                        {
                            m_value = spec_m.Total;
                        }
                        if (!tsTbSpec.ContainsKey(m.Id))
                        {
                            tsTbSpec.Add(m.Id, m_value);
                        }
                        else
                        {
                            tsTbSpec[m.Id] = tsTbSpec[m.Id] + m_value;
                        }
                        allTotal += m_value;
                        //GetNumber(m_value.ToString());

                        if (index < sumCount - 1)
                        {
                            GetNumber(m_value.ToString("n2"));
                        }
                        else
                        {
                            report1_String += GetNumber_String(m_value.ToString("n2"));
                        }
                    }
                    index++;
                }
                u.Total       = allTotal;
                sum_RoadLong += RoadLong;

                report1_String += GetNumber_String(allTotal.ToString("n2"));
                report1_String += GetNumber_String(RoadLong.ToString());
                if (Convert.ToDecimal(lblCarTotal.Text) == 0)
                {
                    report1_String += GetNumber_String("0");
                }
                else
                {
                    report1_String += GetNumber_String(((RoadLong / Convert.ToDecimal(lblCarTotal.Text)) * 100).ToString("n2") + "%");
                }
                report1_String += GetNumber_String(sellT.ToString("n2"));
                report1_String += GetNumber_String(baifenbi.ToString());
                report1_String += "</Row>";
                Response.Write("</Row>");
                Response.Write(report1_String);
                sum_AllTotal += allTotal;

                //Response.Write("</Table>");

                ////第二个表
                //Response.Write(@"<Table x:FullColumns='1' x:FullRows='1'>");

                Response.Write(string.Format("<Row ss:AutoFitHeight='1' ss:colspan='21' ss:style='height: 20px; background-color: #336699; color: White;'>"));

                Response.Write(string.Format("<Cell ss:StyleID='s82'  ss:MergeAcross='10' ><Data ss:Type='String'>公司:{0}</Data></Cell>", lblSimpName.Text));


                Response.Write("</Row>");

                string report2_String = "<Row ss:AutoFitHeight='1'><Cell ss:StyleID='s82'><Data ss:Type='String'> </Data></Cell><Cell ss:StyleID='s82' ss:MergeAcross='9'><Data ss:Type='String'>选中合计</Data></Cell></Row>";
                Response.Write(string.Format("<Row ss:AutoFitHeight='1'>"));
                Response.Write(string.Format("<Cell ss:StyleID='s82'><Data ss:Type='String'> </Data></Cell>", lblYearMonth1.Text));

                Response.Write(string.Format("<Cell ss:StyleID='s82' ss:MergeAcross='9'><Data ss:Type='String'>全年合计</Data></Cell>"));

                //Response.Write(string.Format("<Cell ss:StyleID='s82' ss:MergeAcross='9'><Data ss:Type='String'>选中合计</Data></Cell>"));


                Response.Write("</Row>");
                //body


                Response.Write(string.Format("<Row ss:AutoFitHeight='1'>"));
                Response.Write(string.Format("<Cell ss:StyleID='s82'><Data ss:Type='String'>财年:{0}</Data></Cell>", lblYearMonth1.Text));
                GetHtml_S82("总销售额");
                GetHtml_S82("企业销售额");
                GetHtml_S82("企业利润");
                GetHtml_S82("政府销售额");
                GetHtml_S82("政府利润");
                GetHtml_S82("总成本");
                GetHtml_S82("企业成本");
                GetHtml_S82("政府成本");
                GetHtml_S82("企业净利");
                GetHtml_S82("政府净利");

                report2_String += "<Row ss:AutoFitHeight='1'>";
                report2_String += GetHtml_S82_String("");
                report2_String += GetHtml_S82_String("总销售额");
                report2_String += GetHtml_S82_String("企业销售额");
                report2_String += GetHtml_S82_String("企业利润");
                report2_String += GetHtml_S82_String("政府销售额");
                report2_String += GetHtml_S82_String("政府利润");
                report2_String += GetHtml_S82_String("总成本");
                report2_String += GetHtml_S82_String("企业成本");
                report2_String += GetHtml_S82_String("政府成本");
                report2_String += GetHtml_S82_String("企业净利");
                report2_String += GetHtml_S82_String("政府净利");
                report2_String += "</Row>";
                Response.Write(string.Format("</Row>"));
                decimal SUM_X1  = 0;
                decimal SUM_X6  = 0;
                decimal SUM_X7  = 0;
                decimal SUM_X8  = 0;
                decimal SUM_X9  = 0;
                decimal SUM_X10 = 0;
                decimal SUM_X11 = 0;
                decimal SUM_X16 = 0;
                decimal SUM_X17 = 0;
                decimal SUM_X18 = 0;
                decimal SUM_X19 = 0;
                decimal SUM_X20 = 0;

                decimal AllTotal = 0;
                var     model    = allList.Find(t => t.AE == u.LoginName);
                //foreach (var model in allList)
                //{
                decimal X1 = model.SellTotal_QZ + model.SellTotal_ZZ;
                //var u = user.Find(t => t.LoginName == model.AE);
                decimal X6  = u != null ? u.Total : 0;
                decimal X7  = X1 != 0 ? model.SellTotal_QZ / X1 * X6 : 0;
                decimal X8  = X1 != 0 ? model.SellTotal_ZZ / X1 * X6 : 0;
                decimal X9  = model.MaoLi_QZ - X7;
                decimal X10 = model.MaoLi_ZZ - X8;
                decimal X11 = model.SellTotal_QXZ + model.SellTotal_ZXZ;
                decimal X16 = X1 != 0 ? X11 / X1 * X6 : 0;
                decimal X17 = X11 != 0 ? model.SellTotal_QXZ / X11 * X16 : 0;
                decimal X18 = X11 != 0 ? model.SellTotal_ZXZ / X11 * X16 : 0;
                decimal X19 = model.MaoLi_QXZ - X17;
                decimal X20 = model.MaoLi_ZXZ - X18;
                SUM_X1  += X1;
                SUM_X6  += X6;
                SUM_X7  += X7;
                SUM_X8  += X8;
                SUM_X9  += X9;
                SUM_X10 += X10;
                SUM_X11 += X11;
                SUM_X16 += X16;
                SUM_X17 += X17;
                SUM_X18 += X18;
                SUM_X19 += X19;
                SUM_X20 += X20;
                Response.Write(string.Format("<Row ss:AutoFitHeight='1'>"));

                GetHtml(model.AE);
                GetNumber(X1.ToString());
                GetNumber(model.SellTotal_QZ);
                GetNumber(model.MaoLi_QZ);
                GetNumber(model.SellTotal_ZZ);
                GetNumber(model.MaoLi_ZZ);
                GetNumber(X6.ToString("n4"));
                GetNumber(X7.ToString("n4"));
                GetNumber(X8.ToString("n4"));
                GetNumber(X9.ToString("n4"));
                GetNumber(X10.ToString("n4"));

                report2_String += "<Row ss:AutoFitHeight='1'>";
                report2_String += GetNumber_String(" ");
                report2_String += GetNumber_String(X11.ToString("n4"));
                report2_String += GetNumber_String(model.SellTotal_QXZ);
                report2_String += GetNumber_String(model.MaoLi_QXZ);
                report2_String += GetNumber_String(model.SellTotal_ZXZ);
                report2_String += GetNumber_String(model.MaoLi_ZXZ);
                report2_String += GetNumber_String(X16.ToString("n4"));
                report2_String += GetNumber_String(X17.ToString("n4"));
                report2_String += GetNumber_String(X18.ToString("n4"));
                report2_String += GetNumber_String(X19.ToString("n4"));

                report2_String += GetNumber_String(X20.ToString("n4"));
                report2_String += "</Row>";

                Response.Write("</Row>");
                //}

                Response.Write(report2_String);
                Response.Write("</Table>");

                Response.Write("</Worksheet>");
                Response.Flush();
            }
            Response.Write("</Workbook>");
            Response.End();
        }
Ejemplo n.º 39
0
        private void AddReq(ReqProRequirementPrx reqReqPrx,
                            int nTraceLevel, int nTraceFromHopCount, int nTraceToHopCount, ulong ulDegreeOffset,
                            ReqProRequirementPrx reqReqPrxTracesPreceder)
        {
            ReqTraceNode reqTraceNode = null;

            ReqProRequirementPrx.eTraceAbortReason eAbort = ReqProRequirementPrx.eTraceAbortReason.eNoAbort;

            if (dictReqKey.ContainsKey(reqReqPrx.Key))
            /* this requirement was already handled */
            {
                reqTraceNode = dictReqKey[reqReqPrx.Key];
                if (reqReqPrxTracesPreceder == null)
                {
                    reqTraceNode.MakeRootNode();
                }
                if (!(reqTraceNode.TunedUp(nTraceFromHopCount, nTraceToHopCount)))
                {
                    return;
                }
            }

            if (reqReqPrxTracesPreceder != null)
            {
                if (listnReqTypeTracedKeyExcl.Contains(reqReqPrx.ReqTypeKey))
                {
                    eAbort |= ReqProRequirementPrx.eTraceAbortReason.eReqTypeFilter;
                    showProgressReqTraceGrid(0, 0, "Filtered: " + reqReqPrx.Tag);
                    return;
                }
            }

            int nTracesTo;
            int nTracesFrom;

            ReqProRequirementPrx[] aTracesTo;
            ReqProRequirementPrx[] aTracesFrom;
            ulong ulDegreeInc = 1UL;

            for (int i = 0; i < (nTraceLevel + nMaxLevelTo); i++)
            {
                ulDegreeInc *= ulLevelMultiplier * ((ulong)nTraceLevel + (ulong)nMaxLevelTo);
            }

            Tracer tracer = new Tracer("Traces from/to Req " + reqReqPrx.Tag);

            aTracesTo   = reqReqPrx.GetRequirementTracesTo(nMaxTraceCount, ref eAbort, out nTracesTo, reqReqPrxTracesPreceder);
            aTracesFrom = reqReqPrx.GetRequirementTracesFrom(nMaxTraceCount, ref eAbort, out nTracesFrom, reqReqPrxTracesPreceder);
            tracer.Stop("Traces from/to Req " + reqReqPrx.Tag);

            if (reqTraceNode == null)
            {
                reqTraceNode = new ReqTraceNode(reqReqPrx, ulDegreeOffset, reqReqPrxTracesPreceder == null,
                                                aTracesFrom, aTracesTo, nTracesFrom, nTracesTo, eAbort, nTraceFromHopCount, nTraceToHopCount);
                dictReqKey.Add(reqReqPrx.Key, reqTraceNode);
                grid[TraceLevel2Index(nTraceLevel)].Add(reqTraceNode);
            }
            else
            {
                reqTraceNode.OnceAgain(ulDegreeOffset, reqReqPrxTracesPreceder == null,
                                       aTracesFrom, aTracesTo, nTracesFrom, nTracesTo, eAbort, nTraceFromHopCount, nTraceToHopCount);
            }

            showProgressReqTraceGrid(0, 1, "Adding: " + reqTraceNode.Tag);

            if (aTracesFrom.GetLength(0) > 0)
            {
                if (nTraceLevel < this.nMaxLevelFrom)
                {
                    if (reqTraceNode.TraceFromHopCount < this.nMaxFromTraceHops)
                    {
                        int   nNextTraceFromHopCount = nTraceFromHopCount;
                        ulong ulLocOffset            = ulDegreeOffset * ulLevelMultiplier;
                        showProgressReqTraceGrid(aTracesFrom.GetLength(0), 0, null);
                        foreach (ReqProRequirementPrx reqReqPrxFrom in aTracesFrom)
                        {
                            if (dictReqKey.ContainsKey(reqReqPrxFrom.Key))
                            {
                                ReqTraceNode reqTN = dictReqKey[reqReqPrxFrom.Key];
                                reqTN.SetRelDegree(ulLocOffset);
                                reqTN.AddTraceTo(reqReqPrx);
                            }
                            else
                            {
                                ulLocOffset += ulDegreeInc;
                                AddReq(reqReqPrxFrom, nTraceLevel + 1, ++nNextTraceFromHopCount, nTraceToHopCount,
                                       ulLocOffset, reqReqPrx);
                            }
                        }
                    }
                    else
                    {
                        System.Diagnostics.Trace.WriteLine("From Hops exceeded at: " + reqReqPrx.TagName);
                        showProgressReqTraceGrid(0, 0, "tracing from hops exceeded at: " + reqTraceNode.Tag);
                        eAbort |= ReqProRequirementPrx.eTraceAbortReason.eMaxFromHopsExceeded;
                    }
                }
                else
                {
                    eAbort |= ReqProRequirementPrx.eTraceAbortReason.eMaxFromLevelReached;
                }
            }


            if (aTracesTo.GetLength(0) > 0)
            {
                if (nTraceLevel > -this.nMaxLevelTo)
                {
                    if (reqTraceNode.TraceToHopCount + 1 <= this.nMaxToTraceHops)
                    {
                        int   nNextTraceToHopCount = reqTraceNode.TraceToHopCount + 1;
                        ulong ulLocOffset          = ulDegreeOffset;
                        showProgressReqTraceGrid(aTracesTo.GetLength(0), 0, null);
                        foreach (ReqProRequirementPrx reqReqPrxTo in aTracesTo)
                        {
                            if (dictReqKey.ContainsKey(reqReqPrxTo.Key))
                            {
                                ReqTraceNode reqTN = dictReqKey[reqReqPrxTo.Key];
                                reqTN.SetRelDegree(ulLocOffset);
                                reqTN.AddTraceFrom(reqReqPrx);
                            }
                            else
                            {
                                ulLocOffset += ulDegreeInc;
                                AddReq(reqReqPrxTo, nTraceLevel - 1, nTraceFromHopCount, nTraceToHopCount,
                                       ulLocOffset, reqReqPrx);
                            }
                        }
                    }
                    else
                    {
                        System.Diagnostics.Trace.WriteLine("To Hops exceeded at: " + reqReqPrx.TagName);
                        showProgressReqTraceGrid(0, 0, "tracing to exceeded at: " + reqTraceNode.Tag);
                        eAbort |= ReqProRequirementPrx.eTraceAbortReason.eMaxToHopsExceeded;
                    }
                }
                else
                {
                    eAbort |= ReqProRequirementPrx.eTraceAbortReason.eMaxToLevelReached;
                }
            }
            reqTraceNode.AbortReason = eAbort;
        }
Ejemplo n.º 40
0
        static Dictionary <string, string> GetSharedCalendarFolders(ExchangeService service, String mbMailboxname)
        {
            Dictionary <String, String> rtList = new System.Collections.Generic.Dictionary <string, String>();

            FolderId           rfRootFolderid = new FolderId(WellKnownFolderName.Root, mbMailboxname);
            FolderView         fvFolderView   = new FolderView(int.MaxValue);
            SearchFilter       sfSearchFilter = new SearchFilter.IsEqualTo(FolderSchema.DisplayName, "Common Views");
            FindFoldersResults ffoldres       = service.FindFolders(rfRootFolderid, sfSearchFilter, fvFolderView);

            if (ffoldres.Folders.Count >= 1)
            {
                PropertySet psPropset = new PropertySet(BasePropertySet.FirstClassProperties);
                ExtendedPropertyDefinition PidTagWlinkAddressBookEID = new ExtendedPropertyDefinition(0x6854, MapiPropertyType.Binary);
                ExtendedPropertyDefinition PidTagWlinkGroupName      = new ExtendedPropertyDefinition(0x6851, MapiPropertyType.String);

                psPropset.Add(PidTagWlinkAddressBookEID);
                ItemView iv = new ItemView(1000);
                iv.PropertySet = psPropset;
                iv.Traversal   = ItemTraversal.Associated;

                SearchFilter cntSearch = new SearchFilter.IsEqualTo(PidTagWlinkGroupName, "People's Calendars");
                // Can also find this using PidTagWlinkType = wblSharedFolder
                FindItemsResults <Item> fiResults = ffoldres.Folders[0].FindItems(cntSearch, iv);
                foreach (Item itItem in fiResults.Items)
                {
                    try
                    {
                        object GroupName           = null;
                        object WlinkAddressBookEID = null;

                        if (itItem.TryGetProperty(PidTagWlinkAddressBookEID, out WlinkAddressBookEID))
                        {
                            byte[] ssStoreID    = (byte[])WlinkAddressBookEID;
                            int    leLegDnStart = 0;

                            String lnLegDN = "";
                            for (int ssArraynum = (ssStoreID.Length - 2); ssArraynum != 0; ssArraynum--)
                            {
                                if (ssStoreID[ssArraynum] == 0)
                                {
                                    leLegDnStart = ssArraynum;
                                    lnLegDN      = System.Text.ASCIIEncoding.ASCII.GetString(ssStoreID, leLegDnStart + 1, (ssStoreID.Length - (leLegDnStart + 2)));
                                    ssArraynum   = 1;
                                }
                            }
                            NameResolutionCollection ncCol = service.ResolveName(lnLegDN, ResolveNameSearchLocation.DirectoryOnly, true);
                            if (ncCol.Count > 0)
                            {
                                //Console.WriteLine(ncCol[0].Contact.DisplayName);
                                FolderId SharedCalendarId = new FolderId(WellKnownFolderName.Calendar, ncCol[0].Mailbox.Address);
                                // Folder SharedCalendaFolder = Folder.Bind(service, SharedCalendarId);
                                CalendarFolder calendar = CalendarFolder.Bind(service, new FolderId(WellKnownFolderName.Calendar, ncCol[0].Mailbox.Address), new PropertySet());
                                rtList.Add(ncCol[0].Contact.DisplayName, ncCol[0].Mailbox.Address);
                            }
                        }
                    }
                    catch (Exception exception)
                    {
                        Console.WriteLine(exception.Message);
                    }
                }
            }
            return(rtList);
        }
Ejemplo n.º 41
0
        public AbstractSocketData decode()
        {
            string @string = System.Text.Encoding.UTF8.GetString(this.dataBytes, 0, this.dataLenth);

            string[] separator = new string[]
            {
                "{|}"
            };
            string[] array = @string.Split(separator, System.StringSplitOptions.RemoveEmptyEntries);
            if (array == null || array.Length < 1)
            {
                return(this.getSocketData(this.dataLenth, this.dataBytes, this.target, this.port));
            }
            string[] separator2 = new string[]
            {
                "{&}"
            };
            System.Collections.Generic.IDictionary <string, object> dictionary = new System.Collections.Generic.Dictionary <string, object>();
            string text = string.Empty;

            string[] array2 = array;
            for (int i = 0; i < array2.Length; i++)
            {
                string   text2  = array2[i];
                string[] array3 = text2.Split(separator2, System.StringSplitOptions.RemoveEmptyEntries);
                if (array3 != null && array3.Length == 2)
                {
                    if ("type".Equals(array3[0]))
                    {
                        text = array3[1];
                    }
                    else
                    {
                        dictionary.Add(array3[0], array3[1]);
                    }
                }
            }
            if (text == null || text.Equals(""))
            {
                return(this.getSocketData(this.dataLenth, this.dataBytes, this.target, this.port));
            }
            System.Type type = System.Type.GetType(text);
            if (type == null)
            {
                throw new System.Exception("getAssamble() is implemented incorrectly.");
            }
            AbstractSocketData abstractSocketData = null;

            try
            {
                abstractSocketData = (AbstractSocketData)ReflactUtil.newInstance(type, null);
            }
            catch (System.Exception)
            {
                throw new System.Exception("There is no default constructor in this type " + type);
            }
            System.Reflection.FieldInfo[] fieldInfos = ReflactUtil.getFieldInfos(type);
            System.Reflection.FieldInfo[] array4     = fieldInfos;
            for (int j = 0; j < array4.Length; j++)
            {
                System.Reflection.FieldInfo fieldInfo = array4[j];
                string name = fieldInfo.Name;
                if (dictionary.ContainsKey(name))
                {
                    string value = (string)dictionary[name];
                    if (fieldInfo.FieldType.Equals(typeof(byte)))
                    {
                        fieldInfo.SetValue(abstractSocketData, System.Convert.ToByte(value));
                    }
                    else
                    {
                        if (fieldInfo.FieldType.Equals(typeof(char)))
                        {
                            fieldInfo.SetValue(abstractSocketData, System.Convert.ToChar(value));
                        }
                        else
                        {
                            if (fieldInfo.FieldType.Equals(typeof(short)))
                            {
                                fieldInfo.SetValue(abstractSocketData, System.Convert.ToInt16(value));
                            }
                            else
                            {
                                if (fieldInfo.FieldType.Equals(typeof(int)))
                                {
                                    fieldInfo.SetValue(abstractSocketData, System.Convert.ToInt32(value));
                                }
                                else
                                {
                                    if (fieldInfo.FieldType.Equals(typeof(long)))
                                    {
                                        fieldInfo.SetValue(abstractSocketData, System.Convert.ToInt64(value));
                                    }
                                    else
                                    {
                                        if (fieldInfo.FieldType.Equals(typeof(double)))
                                        {
                                            fieldInfo.SetValue(abstractSocketData, System.Convert.ToDouble(value));
                                        }
                                        else
                                        {
                                            if (fieldInfo.FieldType.Equals(typeof(float)))
                                            {
                                                fieldInfo.SetValue(abstractSocketData, System.Convert.ToSingle(value));
                                            }
                                            else
                                            {
                                                if (fieldInfo.FieldType.Equals(typeof(string)))
                                                {
                                                    fieldInfo.SetValue(abstractSocketData, value);
                                                }
                                                else
                                                {
                                                    if (fieldInfo.FieldType.Equals(typeof(bool)))
                                                    {
                                                        fieldInfo.SetValue(abstractSocketData, System.Convert.ToBoolean(value));
                                                    }
                                                    else
                                                    {
                                                        if (fieldInfo.FieldType.Equals(typeof(System.DateTime)))
                                                        {
                                                            fieldInfo.SetValue(abstractSocketData, System.Convert.ToDateTime(value));
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return(abstractSocketData);
        }
Ejemplo n.º 42
0
        public Comunicazioni(TipoCanale canaleType, List <DataRow> _list)
        {
            this.ComFlussi = new Dictionary <TipoCanale, List <ComFlusso> >();
            this.ComFlussi.Add(canaleType, null);
            if (_list[0].Table.Columns.Contains("ANN_PRT"))
            {
                this.annPrt = _list[0].Field <string>("ANN_PRT");
                this.numPrt = _list[0].Field <string>("NUM_PRT");
            }
            if (_list[0].Table.Columns.Contains("COD_IND"))
            {
                this.CodiceIndividuale = _list[0].Field <string>("COD_IND");
            }
            this.ComCode         = _list[0].Field <String>("TIP_RIC");
            this.StringaID       = _list[0].Field <String>("STRINGA_ID");
            this.destinatariCode = _list[0].Field <String>("COD_DESTINATARIO").Split(';');
            string             oggetto = string.Empty;
            List <ComAllegato> lAll    = new List <ComAllegato>();
            StringBuilder      dati    = new StringBuilder();

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

            if (_list == null && _list.Count == 0)
            {
                this.ComAllegati = null;
            }
            else
            {
                for (int i = 0; i < _list.Count; i++)
                {
                    if ((_list[i].Field <String>("NOME_TPU").ToUpper().Trim() == "TESTO_MAIL") || (_list[i].Field <String>("NOME_TPU").ToUpper().Trim() == "TESTO_MAIL_ELE"))
                    {
                        dati.Append(_list[i].Field <String>("DATI_PRU"));
                    }
                    if (_list[i].Field <string>("NOME_TPU").ToUpper().Trim() == "OGGETTO_MAIL_ELE")
                    {
                        oggetto += _list[i].Field <string>("DATI_PRU");
                        continue;
                    }

                    if (!(string.IsNullOrEmpty(_list[i].Field <String>("PROG_PRU")) || _list[i].Field <String>("NOME_TPU").ToLower().Equals("testo_mail") || _list[i].Field <String>("NOME_TPU").ToLower().Equals("testo_mail_ele")))
                    {
                        if (!prus.ContainsKey(int.Parse(_list[i].Field <String>("PROG_TPU").Trim())))
                        {
                            prus.Add(int.Parse(_list[i].Field <String>("PROG_TPU").Trim()), string.Empty);
                            tpus.Add(int.Parse(_list[i].Field <String>("PROG_TPU").Trim()), _list[i].Field <String>("NOME_TPU"));
                        }
                        prus[int.Parse(_list[i].Field <String>("PROG_TPU").Trim())] = prus[int.Parse(_list[i].Field <String>("PROG_TPU").Trim())] + _list[i].Field <String>("DATI_PRU");
                    }
                }

                for (int j = 0; j < tpus.Count; j++)
                {
                    ComAllegato a = new ComAllegato();
                    a.IdAllegato   = null;
                    a.RefIdCom     = null;
                    a.AllegatoTpu  = tpus[j + 1];
                    a.T_Progr      = j;
                    a.AllegatoExt  = "PRU";
                    a.AllegatoFile = Encoding.GetEncoding("ISO-8859-1").GetBytes(prus[j + 1]);
                    a.AllegatoFile = new UTF8Encoding(false).GetBytes(prus[j + 1]);
                    string[] cmp = tpus[j + 1].Split('.');
                    a.AllegatoName = String.Format("{0}_{1}", String.Join(".", cmp, 0, cmp.Length - 1), (j + 1).ToString("D3"));
                    lAll.Add(a);
                }
                this.ComAllegati = lAll;
            }

            switch (canaleType)
            {
            case TipoCanale.MAIL:
                this.MailComunicazione               = new MailContent();
                this.MailComunicazione.MailSender    = _list[0].Field <String>("EMAIL");
                this.MailComunicazione.MailText      = dati.ToString();
                this.MailComunicazione.HasCustomRefs = false;
                if (!string.IsNullOrEmpty(oggetto))
                {
                    this.MailComunicazione.MailSubject = oggetto.Trim();
                }
                break;

            default:
                break;
            }
        }
Ejemplo n.º 43
0
        public void a(string url)
        {
            string result = ""; //for the result of running cmd program
            string output = "";


            //the path to the downloader

            string path; //= @"cd C:\Users\Admin\Desktop\youtubeVidyabot\youtubeVidyabot\bin\Debug";

            path  = "cd " + System.Environment.CurrentDirectory;
            path += " &&node ytdl -o " + @" ""{ { author.name} } "" " + url + " audioonly";


            // create the ProcessStartInfo using "cmd" as the program to be run,
            // and "/c " as the parameters.
            // Incidentally, /c tells cmd that we want it to execute the command that follows,
            // and then exit.
            System.Diagnostics.ProcessStartInfo procStartInfo =
                new System.Diagnostics.ProcessStartInfo("cmd", "/c " + path);

            // The following commands are needed to redirect the standard output.
            // This means that it will be redirected to the Process.StandardOutput StreamReader.
            procStartInfo.RedirectStandardOutput = true;
            procStartInfo.UseShellExecute        = false;
            // Do not create the black window.
            procStartInfo.CreateNoWindow = true;
            // Now we create a process, assign its ProcessStartInfo and start it
            System.Diagnostics.Process proc = new System.Diagnostics.Process();
            proc.StartInfo = procStartInfo;
            proc.Start();

            // Get the output into a string
            result = proc.StandardOutput.ReadToEnd();
            output = result;



            //extract the song's name from the downloaded json
            string[] endline = output.Split(new char[] { '\n' });


            System.Collections.Generic.Dictionary <string, string> items = new System.Collections.Generic.Dictionary <string, string>();
            foreach (string item in endline)
            {
                if (item != "")
                {
                    string[] linetoks = item.Split(new char[] { ':' });
                    foreach (var c in System.IO.Path.GetInvalidFileNameChars())//also replace characters which make filenames invalid
                    {
                        linetoks[1] = linetoks[1].Replace(c, '-');
                    }
                    items.Add(linetoks[0], linetoks[1]);
                }
            }

            System.Threading.Thread.Sleep(2000);



            //ADD BAD CHARACTER CHECKING IN HERE

            //find the song in the filesystem to rename it later
            string[] files =
                System.IO.Directory.GetFiles(System.Environment.CurrentDirectory);
            string FILE_NAME = "";

            foreach (string item in files)
            {
                if (item.Contains("author.name"))
                {
                    FILE_NAME = item;
                    break;
                }
            }


            System.IO.File.Move(FILE_NAME, items["title"]);//rename it, items title must always be a proper filename


            path = null;
            //  path = @"cd C:\Users\Admin\Desktop\youtubeVidyabot\youtubeVidyabot\bin\Debug";
            path  = "cd " + System.Environment.CurrentDirectory;
            path += " && ffmpeg.exe -i " + " " + '"' + items["title"] + '"' + " " + '"' + items["title"] + '"' + ".mp3";



            // create the ProcessStartInfo using "cmd" as the program to be run,
            // and "/c " as the parameters.
            // Incidentally, /c tells cmd that we want it to execute the command that follows,
            // and then exit.
            System.Diagnostics.ProcessStartInfo procStartInfo2 =
                new System.Diagnostics.ProcessStartInfo("cmd", "/c " + path);

            // The following commands are needed to redirect the standard output.
            // This means that it will be redirected to the Process.StandardOutput StreamReader.
            procStartInfo2.RedirectStandardOutput = true;
            procStartInfo2.UseShellExecute        = false;
            // Do not create the black window.
            procStartInfo2.CreateNoWindow = true;
            // Now we create a process, assign its ProcessStartInfo and start it
            System.Diagnostics.Process proc2 = new System.Diagnostics.Process();
            proc2.StartInfo = procStartInfo2;
            proc2.Start();

            // Get the output into a string
            result = proc2.StandardOutput.ReadToEnd();
            output = result;



            System.IO.File.Move(items["title"] + ".mp3", "mp3s\\" + items["title"] + ".mp3");
            System.IO.File.Delete(items["title"] + ".mp3"); //cleanup
        }
Ejemplo n.º 44
0
    protected void ImportResource(DataTable dtExcelInfo, System.Collections.Generic.Dictionary <string, int> dicRes)
    {
        System.Collections.Generic.List <string> priceTypeCodes = ResPriceType.GetPriceTypeCodes();
        string text = PageHelper.QueryUser(this, base.UserCode);
        int    num  = 0;

        for (int i = 0; i < dtExcelInfo.Rows.Count; i++)
        {
            DataRow dataRow = dtExcelInfo.Rows[i];
            string  text2   = dataRow[dicRes["ResourceCode"]].ToString();
            bool    flag    = this.IsExistResourceCode(text2);
            if (flag)
            {
                Label  expr_57 = this.lblErrorMsg;
                string text3   = expr_57.Text;
                expr_57.Text = string.Concat(new string[]
                {
                    text3,
                    "<div align='left' style=' margin-top:3px; padding-left:15px;  border-bottom-style:solid; border-bottom-color:#cccccc; border-bottom-width:1px;  background-color:white; line-height:28px; height:28px; text-align:left;'>在您的Excel中:",
                    dtExcelInfo.Columns[dicRes["ResourceCode"]].ColumnName,
                    "<span style='color:green;'>",
                    text2,
                    "</span>,此编码已经存在导入失败!</div>"
                });
            }
            else
            {
                string text4 = dtExcelInfo.Rows[i][dicRes["ResourceName"]].ToString();
                if (!string.IsNullOrEmpty(text2) && !string.IsNullOrEmpty(text4))
                {
                    string  brand   = dicRes.Keys.Any((string a) => a == "Brand") ? dataRow[dicRes["Brand"]].ToString() : string.Empty;
                    string  text5   = dicRes.Keys.Any((string a) => a == "TaxRate") ? dataRow[dicRes["TaxRate"]].ToString() : string.Empty;
                    decimal?taxRate = null;
                    decimal value;
                    if (!string.IsNullOrEmpty(text5) && decimal.TryParse(text5, out value))
                    {
                        taxRate = new decimal?(value);
                    }
                    string specification  = dicRes.Keys.Any((string a) => a == "Specification") ? dataRow[dicRes["Specification"]].ToString() : string.Empty;
                    string technicalParam = dicRes.Keys.Any((string a) => a == "TechnicalParameter") ? dataRow[dicRes["TechnicalParameter"]].ToString() : string.Empty;
                    string text6          = dicRes.Keys.Any((string a) => a == "Unit") ? dataRow[dicRes["Unit"]].ToString() : string.Empty;
                    if (string.IsNullOrEmpty(text6))
                    {
                        text6 = "xx";
                    }
                    string attributeName    = dicRes.Keys.Any((string a) => a == "Attribute") ? dataRow[dicRes["Attribute"]].ToString() : string.Empty;
                    string series           = dicRes.Keys.Any((string a) => a == "Series") ? dataRow[dicRes["Series"]].ToString() : string.Empty;
                    string supplierName     = dicRes.Keys.Any((string a) => a == "SupplierId") ? dataRow[dicRes["SupplierId"]].ToString() : string.Empty;
                    int?   supplierIdByName = cn.justwin.Domain.Resource.GetSupplierIdByName(supplierName);
                    string modelNumber      = dicRes.Keys.Any((string a) => a == "ModelNumber") ? dataRow[dicRes["ModelNumber"]].ToString() : string.Empty;
                    if (!dicRes.Keys.Any((string a) => a == "Note"))
                    {
                        string arg_400_0 = string.Empty;
                    }
                    else
                    {
                        dataRow[dicRes["Note"]].ToString();
                    }
                    System.Collections.Generic.Dictionary <ResPriceType, decimal?> dictionary = new System.Collections.Generic.Dictionary <ResPriceType, decimal?>();
                    foreach (string key in dicRes.Keys)
                    {
                        bool flag2 = priceTypeCodes.Any((string a) => a == key);
                        if (flag2)
                        {
                            string  s = dataRow[dicRes[key]].ToString();
                            decimal value2;
                            decimal.TryParse(s, out value2);
                            dictionary.Add(ResPriceType.GetByTypeCode(key), new decimal?(value2));
                        }
                    }
                    ResType                    byId            = ResType.GetById(base.Request["parentId"]);
                    ResUnit                    unit            = this.GetUnit(text6, text);
                    ResTypeAttribute           byAttributeName = ResTypeAttribute.GetByAttributeName(attributeName);
                    cn.justwin.Domain.Resource resource        = cn.justwin.Domain.Resource.Create(System.Guid.NewGuid().ToString(), byId, text2, text4, brand, taxRate, specification, modelNumber, technicalParam, unit, byAttributeName, series, dictionary, text, new System.DateTime?(System.DateTime.Now), supplierIdByName);
                    cn.justwin.Domain.Resource.Add(resource);
                    num++;
                }
            }
        }
        if (num == 0)
        {
            base.RegisterScript("alert('系统提示:\\n数据导入失败!');setTem('2');");
            return;
        }
        if (num == dtExcelInfo.Rows.Count)
        {
            base.RegisterScript("alert('系统提示:\\n数据导入成功!');setTem('2');closePage();");
            return;
        }
        base.RegisterScript("alert('系统提示:\\n数据导入成功!');setTem('2');");
    }
Ejemplo n.º 45
0
    protected void Guardar_Actualizar(object sender, EventArgs e)
    {
        if (txtNombre.Text.Trim().Equals(""))
        {
            //popUpMessageControl1.setAndShowInfoMessage("El campo nombre es requerido.", Common.MESSAGE_TYPE.Error);
            popUpMessageControl1.setAndShowInfoMessage(string.Format((string)GetLocalResourceObject("NombreRequerido").ToString()), Common.MESSAGE_TYPE.Error);
        }
        else
        {
            Dictionary <string, object> parameters = new System.Collections.Generic.Dictionary <string, object>();
            parameters.Add("@nombre", txtNombre.Text);
            parameters.Add("@descripcion", txtDescripcion.Text);
            if (chkActivo.Checked)
            {
                parameters.Add("@activo", 1);
            }
            else
            {
                parameters.Add("@activo", 0);
            }

            if (Accion.Value == "Añadir")
            {
                Dictionary <string, object> find = new System.Collections.Generic.Dictionary <string, object>();
                find.Add("@nombre", txtNombre.Text);

                if (DataAccess.executeStoreProcedureGetInt("spr_ExisteEquipoAplicacion", find, this.Session["connection"].ToString()) > 0)
                {
                    //popUpMessageControl1.setAndShowInfoMessage("No se efectuarán cambios debido a que el tipo de Aplicacion ya existe.", Common.MESSAGE_TYPE.Info);
                    popUpMessageControl1.setAndShowInfoMessage(string.Format((string)GetLocalResourceObject("YaExiste").ToString()), Common.MESSAGE_TYPE.Error);
                }
                else
                {
                    String Rs = DataAccess.executeStoreProcedureString("spr_InsertEquipoAplicacion", parameters, this.Session["connection"].ToString());
                    if (Rs.Equals("Repetido"))
                    {
                        //popUpMessageControl1.setAndShowInfoMessage("Ese registro ya había sido capturado.", Common.MESSAGE_TYPE.Error);
                        popUpMessageControl1.setAndShowInfoMessage(string.Format((string)GetLocalResourceObject("yaExiste2").ToString()), Common.MESSAGE_TYPE.Error);
                    }
                    else
                    {
                        //popUpMessageControl1.setAndShowInfoMessage("El Modulo \"" + txtNombre.Text + "\" se guardó exitosamente.", Common.MESSAGE_TYPE.Success);
                        popUpMessageControl1.setAndShowInfoMessage(string.Format((string)GetLocalResourceObject("EquipoGuardado"), txtNombre.Text.ToString()), Common.MESSAGE_TYPE.Success);
                    }
                }
            }
            else
            {
                if (Session["idEquipoAplicacionCookie"] == null || Session["idEquipoAplicacionCookie"].ToString() == "")
                {
                    //popUpMessageControl1.setAndShowInfoMessage("Error #RGRL02: Se perdió la información del ID actual", Common.MESSAGE_TYPE.Error);
                    popUpMessageControl1.setAndShowInfoMessage(string.Format((string)GetLocalResourceObject("RGRL02").ToString()), Common.MESSAGE_TYPE.Error);
                }
                else
                {
                    parameters.Add("@IdEquipoAplicacion", Session["idEquipoAplicacionCookie"].ToString());
                    String Rs = DataAccess.executeStoreProcedureString("spr_UpdateEquipoAplicacion", parameters, this.Session["connection"].ToString());
                    if (Rs.Equals("error"))
                    {
                        //popUpMessageControl1.setAndShowInfoMessage("No se efectuarán cambios intentelo de nuevo.", Common.MESSAGE_TYPE.Info);
                        popUpMessageControl1.setAndShowInfoMessage(string.Format((string)GetLocalResourceObject("NoCambios").ToString()), Common.MESSAGE_TYPE.Error);
                    }
                    else
                    {
                        //popUpMessageControl1.setAndShowInfoMessage("Cambios realizados.", Common.MESSAGE_TYPE.Success);
                        popUpMessageControl1.setAndShowInfoMessage(string.Format((string)GetLocalResourceObject("CambiosExito").ToString()), Common.MESSAGE_TYPE.Success);
                    }
                }
            }
            obtieneTiposAplicacion();
            VolverAlPanelInicial();
        }
    }
Ejemplo n.º 46
0
 public void AddInt(string columnName, int?value)
 {
     if (value.HasValue)
     {
         htData.Add(columnName, objFucntion.ValueCheck(value.ToString()));
     }
     else
     {
         htData.Add(columnName, "NULL");
     }
 }
Ejemplo n.º 47
0
        public void FillIn_NotSelectedConditionFieldWithSubComponentRequiredShouldBeSave()
        {
            FormViewModel formViewModel = new FormViewModel();

            formViewModel.Title = "Required Form Name";
            Template template = _formManager.CreateNewFormAndTemplate(formViewModel);

            Assert.IsNotNull(template);

            TemplateViewModel templateViewModel = _formManager.FindTemplateToEdit(template.TemplateID);

            FormCollection fieldCollection = new FormCollection();
            IDictionary <string, string> fields;

            CeateFieldForm(1, Constants.TemplateFieldType.RADIOBUTTON.ToString(), fieldCollection, out fields);
            fieldCollection.Set("Fields[" + 1 + "].Label", "Radio Button");
            fieldCollection.Set("Fields[" + 1 + "].IsRequired", "true");
            fieldCollection.Add("Fields[" + 1 + "].Options", "Yes,No");

            _formManager.UpdateTemplate(templateViewModel, fieldCollection, fields);

            CeateFieldForm(2, Constants.TemplateFieldType.RADIOBUTTON.ToString(), fieldCollection, out fields);
            fieldCollection.Set("Fields[" + 2 + "].Label", "Radio Button Yes");
            fieldCollection.Set("Fields[" + 2 + "].IsRequired", "true");
            fieldCollection.Add("Fields[" + 2 + "].ConditionTemplateFieldID", "1");
            fieldCollection.Add("Fields[" + 2 + "].ConditionCriteria", "==");
            fieldCollection.Add("Fields[" + 2 + "].ConditionOptions", "Yes");
            fieldCollection.Add("Fields[" + 1 + "].Options", "Yes,No");

            _formManager.UpdateTemplate(templateViewModel, fieldCollection, fields);

            CeateFieldForm(3, Constants.TemplateFieldType.TEXTBOX.ToString(), fieldCollection, out fields);
            fieldCollection.Set("Fields[" + 3 + "].Label", "Radio Button No");
            fieldCollection.Set("Fields[" + 3 + "].IsRequired", "true");
            fieldCollection.Add("Fields[" + 3 + "].ConditionTemplateFieldID", "1");
            fieldCollection.Add("Fields[" + 3 + "].ConditionCriteria", "==");
            fieldCollection.Add("Fields[" + 3 + "].ConditionOptions", "No");

            _formManager.UpdateTemplate(templateViewModel, fieldCollection, fields);

            CeateFieldForm(4, Constants.TemplateFieldType.TEXTBOX.ToString(), fieldCollection, out fields);
            fieldCollection.Set("Fields[" + 4 + "].Label", "Radio Button Yes Yes");
            fieldCollection.Set("Fields[" + 4 + "].IsRequired", "true");
            fieldCollection.Add("Fields[" + 4 + "].ConditionTemplateFieldID", "2");
            fieldCollection.Add("Fields[" + 4 + "].ConditionCriteria", "==");
            fieldCollection.Add("Fields[" + 4 + "].ConditionOptions", "Yes");

            _formManager.UpdateTemplate(templateViewModel, fieldCollection, fields);

            CeateFieldForm(5, Constants.TemplateFieldType.TEXTBOX.ToString(), fieldCollection, out fields);
            fieldCollection.Set("Fields[" + 5 + "].Label", "Radio Button Yes No");
            fieldCollection.Set("Fields[" + 5 + "].IsRequired", "true");
            fieldCollection.Add("Fields[" + 5 + "].ConditionTemplateFieldID", "2");
            fieldCollection.Add("Fields[" + 5 + "].ConditionCriteria", "==");
            fieldCollection.Add("Fields[" + 5 + "].ConditionOptions", "No");

            _formManager.UpdateTemplate(templateViewModel, fieldCollection, fields);

            templateViewModel = _formManager.FindTemplateToEdit(template.TemplateID);
            Assert.IsNotNull(templateViewModel.Fields);
            Assert.AreEqual(5, templateViewModel.Fields.Count);

            templateViewModel.Entries = _formManager.HasSubmissions(templateViewModel).ToList();
            Assert.AreEqual(0, templateViewModel.Entries.Count);

            FormCollection submissionCollection = new FormCollection();

            submissionCollection.Add("SubmitFields[1].RadioButton", "Yes");
            submissionCollection.Add("SubmitFields[2].RadioButton", "Yes");
            submissionCollection.Add("SubmitFields[3].TextBox", "i not supposed to be saved 1");
            submissionCollection.Add("SubmitFields[4].TextBox", "Testing 123");
            submissionCollection.Add("SubmitFields[5].TextBox", "i not supposed to be saved 2");

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

            submissionFields.Add("1", "1");
            submissionFields.Add("2", "3");
            submissionFields.Add("3", "3");
            submissionFields.Add("4", "4");
            submissionFields.Add("5", "5");

            string result = _target.FillIn(submissionFields, templateViewModel, submissionCollection);

            Assert.AreEqual("success", result);

            templateViewModel.Entries = _formManager.HasSubmissions(templateViewModel).ToList();

            Assert.AreEqual(0, _unitOfWork.PreRegistrations.GetAll().Count());

            Assert.AreEqual(3, templateViewModel.Entries.Count);

            Assert.AreEqual("Yes", templateViewModel.Entries[0].Value);
            Assert.AreEqual("Yes", templateViewModel.Entries[1].Value);
            Assert.AreEqual("Testing 123", templateViewModel.Entries[2].Value);
        }
Ejemplo n.º 48
0
        // 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.RegistrationTypesRecordControl != null && this.RegistrationTypesRecordControl.DataSource != null)
                    {
                        id = this.RegistrationTypesRecordControl.DataSource.GetValue(this.RegistrationTypesRecordControl.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.RegistrationTypesRecordControl.DataSource.TableAccess.TableDefinition.TableCodeName, this.RegistrationTypesRecordControl.DataSource);
                            value = EvaluateFormula(formula, this.RegistrationTypesRecordControl.DataSource, null, variables);
                        }
                        else if (displayFieldName == "")
                        {
                            value = id;
                        }
                        else
                        {
                            value = this.RegistrationTypesRecordControl.DataSource.GetValue(this.RegistrationTypesRecordControl.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();
            }
        }
Ejemplo n.º 49
0
    protected void Guardar_Actualizar(object sender, EventArgs e)
    {
        if (txtNombre.Text.Trim().Equals(""))
        {
            popUpMessageControl1.setAndShowInfoMessage((string)GetLocalResourceObject("required"), Common.MESSAGE_TYPE.Error);
        }
        else
        {
            try
            {
                Dictionary <string, object> parameters = new System.Collections.Generic.Dictionary <string, object>();
                parameters.Add("@nombre", txtNombre.Text);
                parameters.Add("@descripcion", txtDescripcion.Text);
                if (chkActivo.Checked)
                {
                    parameters.Add("@activo", 1);
                }
                else
                {
                    parameters.Add("@activo", 0);
                }

                if (Accion.Value == "Añadir")
                {
                    Dictionary <string, object> find = new System.Collections.Generic.Dictionary <string, object>();
                    find.Add("@nombre", txtNombre.Text);

                    if (DataAccess.executeStoreProcedureGetInt("spr_ExisteTipoBoquilla", find, this.Session["connection"].ToString()) > 0)
                    {
                        popUpMessageControl1.setAndShowInfoMessage((string)GetLocalResourceObject("exist"), Common.MESSAGE_TYPE.Info);
                    }
                    else
                    {
                        String Rs = DataAccess.executeStoreProcedureString("spr_InsertTipoBoquilla", parameters, this.Session["connection"].ToString());
                        if (Rs.Equals("Repetido"))
                        {
                            popUpMessageControl1.setAndShowInfoMessage((string)GetLocalResourceObject("exist"), Common.MESSAGE_TYPE.Error);
                        }
                        else
                        {
                            popUpMessageControl1.setAndShowInfoMessage(string.Format((string)GetLocalResourceObject("saveIt"), txtNombre.Text), Common.MESSAGE_TYPE.Success);
                        }
                    }
                }
                else
                {
                    if (Session["idTipoBoquillaCookie"] == null || Session["idTipoBoquillaCookie"].ToString() == "")
                    {
                        popUpMessageControl1.setAndShowInfoMessage((string)GetLocalResourceObject("RGRL02"), Common.MESSAGE_TYPE.Error);
                    }
                    else
                    {
                        parameters.Add("@IdTipoBoquilla", Session["idTipoBoquillaCookie"].ToString());
                        String Rs = DataAccess.executeStoreProcedureString("spr_UpdateTipoBoquilla", parameters, this.Session["connection"].ToString());
                        if (Rs.Equals("error"))
                        {
                            popUpMessageControl1.setAndShowInfoMessage((string)GetLocalResourceObject("nochanges"), Common.MESSAGE_TYPE.Info);
                        }
                        else
                        {
                            popUpMessageControl1.setAndShowInfoMessage((string)GetLocalResourceObject("saved"), Common.MESSAGE_TYPE.Success);
                        }
                    }
                }
                obtieneTiposBoquilla();
                VolverAlPanelInicial();
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                popUpMessageControl1.setAndShowInfoMessage(ex.Message, Common.MESSAGE_TYPE.Error);
            }
        }
    }
Ejemplo n.º 50
0
        /// <summary>The subSpans are ordered in the same doc, so there is a possible match.
        /// Compute the slop while making the match as short as possible by advancing
        /// all subSpans except the last one in reverse order.
        /// </summary>
        private bool ShrinkToAfterShortestMatch(IState state)
        {
            matchStart = subSpans[subSpans.Length - 1].Start();
            matchEnd   = subSpans[subSpans.Length - 1].End();
            System.Collections.Generic.Dictionary <byte[], byte[]> possibleMatchPayloads = new System.Collections.Generic.Dictionary <byte[], byte[]>();
            if (subSpans[subSpans.Length - 1].IsPayloadAvailable())
            {
                System.Collections.Generic.ICollection <byte[]> payload = subSpans[subSpans.Length - 1].GetPayload(state);
                foreach (byte[] pl in payload)
                {
                    if (!possibleMatchPayloads.ContainsKey(pl))
                    {
                        possibleMatchPayloads.Add(pl, pl);
                    }
                }
            }

            System.Collections.Generic.List <byte[]> possiblePayload = null;

            int matchSlop = 0;
            int lastStart = matchStart;
            int lastEnd   = matchEnd;

            for (int i = subSpans.Length - 2; i >= 0; i--)
            {
                Spans prevSpans = subSpans[i];
                if (collectPayloads && prevSpans.IsPayloadAvailable())
                {
                    System.Collections.Generic.ICollection <byte[]> payload = prevSpans.GetPayload(state);
                    possiblePayload = new System.Collections.Generic.List <byte[]>(payload.Count);
                    possiblePayload.AddRange(payload);
                }

                int prevStart = prevSpans.Start();
                int prevEnd   = prevSpans.End();
                while (true)
                {
                    // Advance prevSpans until after (lastStart, lastEnd)
                    if (!prevSpans.Next(state))
                    {
                        inSameDoc = false;
                        more      = false;
                        break;                         // Check remaining subSpans for final match.
                    }
                    else if (matchDoc != prevSpans.Doc())
                    {
                        inSameDoc = false;             // The last subSpans is not advanced here.
                        break;                         // Check remaining subSpans for last match in this document.
                    }
                    else
                    {
                        int ppStart = prevSpans.Start();
                        int ppEnd   = prevSpans.End();                       // Cannot avoid invoking .end()
                        if (!DocSpansOrdered(ppStart, ppEnd, lastStart, lastEnd))
                        {
                            break;                             // Check remaining subSpans.
                        }
                        else
                        {
                            // prevSpans still before (lastStart, lastEnd)
                            prevStart = ppStart;
                            prevEnd   = ppEnd;
                            if (collectPayloads && prevSpans.IsPayloadAvailable())
                            {
                                System.Collections.Generic.ICollection <byte[]> payload = prevSpans.GetPayload(state);
                                possiblePayload = new System.Collections.Generic.List <byte[]>(payload.Count);
                                possiblePayload.AddRange(payload);
                            }
                        }
                    }
                }

                if (collectPayloads && possiblePayload != null)
                {
                    foreach (byte[] pl in possiblePayload)
                    {
                        if (!possibleMatchPayloads.ContainsKey(pl))
                        {
                            possibleMatchPayloads.Add(pl, pl);
                        }
                    }
                }

                System.Diagnostics.Debug.Assert(prevStart <= matchStart);
                if (matchStart > prevEnd)
                {
                    // Only non overlapping spans add to slop.
                    matchSlop += (matchStart - prevEnd);
                }

                /* Do not break on (matchSlop > allowedSlop) here to make sure
                 * that subSpans[0] is advanced after the match, if any.
                 */
                matchStart = prevStart;
                lastStart  = prevStart;
                lastEnd    = prevEnd;
            }

            bool match = matchSlop <= allowedSlop;

            if (collectPayloads && match && possibleMatchPayloads.Count > 0)
            {
                matchPayload.AddRange(possibleMatchPayloads.Keys);
            }

            return(match);            // ordered and allowed slop
        }
Ejemplo n.º 51
0
 public void Declare_Procedure(string name, string[] args, bool[] arg_is_input, bool[] arg_is_output)
 {
     Procedures.Add(name, new MethodInformation(args, arg_is_input, arg_is_output));
 }
Ejemplo n.º 52
0
        public async Task ProcessEventsAsync(PartitionContext context, IEnumerable <EventData> messages)
        {
            foreach (EventData message in messages)
            {
                try
                {
                    Trace.WriteLine("Count: " + ru.numberOfItems + " Partition: " + context.Lease.PartitionId);
                    if (firstMessage)
                    {
                        ru.StartTime     = DateTime.Now;
                        firstMessage     = false;
                        ru.numberOfItems = 0;
                    }
                    int sizeOfChunk = 0;

                    if (RoleEnvironment.IsEmulated)
                    {
                        sizeOfChunk = 100;
                    }
                    else
                    {
                        sizeOfChunk = 10000;
                    }

                    if (ru.numberOfItems == sizeOfChunk)
                    {
                        ru.EndTime   = DateTime.Now;
                        firstMessage = true;

                        // Send to SendQueue
                        string output = JsonConvert.SerializeObject(ru);

                        try
                        {
                            var msg = new BrokeredMessage("EventHubs Metadata");
                            msg.TimeToLive            = TimeSpan.FromMinutes(5);
                            msg.Properties["recunit"] = output;
                            await qclient.SendAsync(msg);
                        }
                        catch (Exception e)
                        {
                            Trace.WriteLine("Exception sending message to metadata queue: " + e.Message);
                        }
                    }

                    ru.numberOfItems++;

                    if (message.Properties.Count > 0)
                    {
                        float  currentEnergyProduction = (float)message.Properties["current"];
                        string key = string.Format("{0}|{1}", message.Properties["panel-id"], message.Properties["field-id"]);
                        if (solarCells.ContainsKey(key))
                        {
                            solarCells[key] += currentEnergyProduction;
                        }
                        else
                        {
                            solarCells.Add(key, currentEnergyProduction);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Trace.WriteLine("Exception in ProcessEventsAsync: " + ex.Message);
                }
            }
        }
Ejemplo n.º 53
0
    IEnumerator UploadFileCo(string uploadURL)
    {
        //Take screen shot
        yield return(new WaitForEndOfFrame());

        Texture2D screenTexture = new Texture2D((int)(FrameCoordinates.size.x - (FrameCoordinates.borderWidth * 2)), (int)(FrameCoordinates.size.y - (FrameCoordinates.borderWidth * 2)), TextureFormat.RGB24, true);

        //screenTexture.ReadPixels(new Rect(FrameCoordinates.left, FrameCoordinates.bottom, FrameCoordinates.size.x, FrameCoordinates.size.y),0,0);
        screenTexture.ReadPixels(new Rect(FrameCoordinates.left + FrameCoordinates.borderWidth, FrameCoordinates.bottom + FrameCoordinates.borderWidth, FrameCoordinates.size.x - (FrameCoordinates.borderWidth * 2), FrameCoordinates.size.y - (FrameCoordinates.borderWidth * 2)), 0, 0);
        //screenTexture.ReadPixels(new Rect(0f, 0f+150, Screen.width, Screen.height-150),0,0);

        screenTexture.Apply();

        //Rotate pictures taken in landscape
        if (!(Input.deviceOrientation == DeviceOrientation.Portrait))
        {
            Debug.Log("###---ORIENTATION SWITCHED TO LANDSCAPE---###");
            Texture2D screenTexture2 = new Texture2D((int)(FrameCoordinates.size.y - (FrameCoordinates.borderWidth * 2)), (int)(FrameCoordinates.size.x - (FrameCoordinates.borderWidth * 2)), TextureFormat.RGB24, true);
            Color32[] pixels         = screenTexture.GetPixels32();
            pixels = ImageManipulation.RotateMatrix(pixels, (int)(FrameCoordinates.size.x - (FrameCoordinates.borderWidth * 2)), (int)(FrameCoordinates.size.y - (FrameCoordinates.borderWidth * 2)));
            screenTexture2.SetPixels32(pixels);
            screenTexture = screenTexture2;
        }

        //Convert image to bytes
        byte[] pData2 = screenTexture.EncodeToJPG();
        //UnityEngine.Object.Destroy(screenTexture);

        loadScreen.SetActive(true);
        //Create post request
        WWWForm postForm = new WWWForm();

        string postData = null;

        //set true for Stroke-Width Transform preprocessing (attempts to remove artifacts that aren't characters)
        bool sw = false;

        if (!sw)
        {
            postData = "--09sad98as09dhidp0a98soakscajbva12\n" +
                       "Content-Type: application/json; charset=UTF-8\n\n" +
                       "{\"engine\":\"tesseract\"}\n\n" +
                       "--09sad98as09dhidp0a98soakscajbva12\n" +
                       "Content-Type: image/jpeg\n" +
                       "Content-Disposition: attachment; filename=\"attachment.txt\". \n\n";
        }
        else
        {
            postData = "--09sad98as09dhidp0a98soakscajbva12\n" +
                       "Content-Type: application/json; charset=UTF-8\n\n" +
                       "{\"engine\":\"tesseract\", \"preprocessors\":[\"stroke-width-transform\"]}\n\n" +
                       "--09sad98as09dhidp0a98soakscajbva12\n" +
                       "Content-Type: image/jpeg\n" +
                       "Content-Disposition: attachment; filename=\"attachment.txt\". \n\n";
        }


        byte[] pData1 = System.Text.Encoding.UTF8.GetBytes(postData.ToCharArray());

        string postDataEnd = "\n--09sad98as09dhidp0a98soakscajbva12--\n";

        byte[] pData3 = System.Text.Encoding.UTF8.GetBytes(postDataEnd.ToCharArray());

        //combine different parts of request into byte array
        byte[] pDataCom = new byte[pData1.Length + pData2.Length + pData3.Length];
        System.Buffer.BlockCopy(pData1, 0, pDataCom, 0, pData1.Length);
        System.Buffer.BlockCopy(pData2, 0, pDataCom, pData1.Length, pData2.Length);
        System.Buffer.BlockCopy(pData3, 0, pDataCom, pData1.Length + pData2.Length, pData3.Length);

        System.Collections.Generic.Dictionary <string, string> headers = new System.Collections.Generic.Dictionary <string, string>();
        headers.Add("Content-Type", "multipart/related;boundary=09sad98as09dhidp0a98soakscajbva12");

        byte[] pData = System.Text.Encoding.UTF8.GetBytes(postData.ToCharArray());

        //Create connection
        WWW upload = new WWW(uploadURL, pDataCom, headers);

        yield return(upload);

        if (upload.error == null)
        {
            Debug.Log("\n\n" + System.DateTime.Now.ToString() + ": OCR RESULT: " + upload.text);
            string result = upload.text.Trim();
            result += "\n";

            MakeDataset(result);
            backBtn.SetActive(true);
            //shareGraph.SetActive(true);
            editGraph.SetActive(true);
            //viewGraphs.SetActive(false);
            takePhoto.SetActive(false);
            frameCanvas.SetActive(false);
        }
        else
        {
            Debug.Log("WWW Error: " + upload.error);
            Debug.Log("WWW Error: " + upload.text);
            loadScreen.SetActive(false);
        }
    }
Ejemplo n.º 54
0
 public static void Register(String key, Object value)
 {
     vars.Add(key, value);
 }
Ejemplo n.º 55
0
    protected void guardar_dosis(object sender, EventArgs e)
    {
        var errors       = false;
        var mensajeError = String.Empty;
        var inputs       = String.Empty;
        var ids          = String.Empty;

        //rellenamos una tabla virtual para mandarla al stored procedure
        DataTable dt = new DataTable();

        dt.Columns.Add("id", typeof(string));
        dt.Columns.Add("valor", typeof(decimal));
        foreach (GridViewRow row in gvDosis.Rows)
        {
            if (row.RowType == DataControlRowType.DataRow)
            {
                var ctlCantidadMinima = row.FindControl("hiddenMinima") as TextBox;
                var ctlCantidadMaxima = row.FindControl("hiddenMaxima") as TextBox;
                var idQuimico         = row.FindControl("idQuimico") as HiddenField;
                var dosisCapturada    = row.FindControl("txtInput") as TextBox;
                var nombreQuimico     = row.FindControl("nombreQuimico") as Label;

                var cantidadIngresada = Double.Parse(dosisCapturada.Text);
                var cantidadMinima    = Double.Parse(ctlCantidadMinima.Text);
                var cantidadMaxima    = Double.Parse(ctlCantidadMaxima.Text);

                //validacion server side de que los campos sean iguales
                if (!(cantidadIngresada >= cantidadMinima && cantidadIngresada <= cantidadMaxima))
                {
                    errors        = true;
                    mensajeError += GetLocalResourceObject("ErrorEn").ToString() + nombreQuimico.Text + GetLocalResourceObject("ErrorRangoFuera").ToString();
                }
                else
                {
                    //si son iguales rellenamos la tabla
                    DataRow dr = dt.NewRow();
                    dr[0] = idQuimico.Value;
                    dr[1] = Double.Parse(dosisCapturada.Text);
                    dt.Rows.Add(dr);
                }
            }
        }

        if (errors)
        {
            popUpMessageControl1.setAndShowInfoMessage(mensajeError, Common.MESSAGE_TYPE.Error);
            this.showPopup();
        }
        else
        {
            try
            {
                Dictionary <string, object> parameters = new System.Collections.Generic.Dictionary <string, object>();
                parameters.Add("@idOTHeader", Session["IdOTCookie"]);
                parameters.Add("@datosCapturados", dt);

                //guarda
                //String Rs = DataAccess.executeStoreProcedureString("spr_UpdateDosisProgramacion", parameters);
                DataTable Rs = DataAccess.executeStoreProcedureDataTable("spr_UpdateDosisProgramacion", parameters, this.Session["connection"].ToString());
                if (Rs.Equals("error"))
                {
                    //popUpMessageControl1.setAndShowInfoMessage("No se efectuarán cambios intentelo de nuevo.", Common.MESSAGE_TYPE.Info);
                    popUpMessageControl1.setAndShowInfoMessage(GetLocalResourceObject("NoCambios").ToString(), Common.MESSAGE_TYPE.Warning);
                }
                else
                {
                    //libera el candado
                    Dictionary <string, object> candado = new System.Collections.Generic.Dictionary <string, object>();
                    candado.Add("@idPrograma", Session["IdOTCookie"]);
                    candado.Add("@candado", 0);
                    DataAccess.executeStoreProcedureDataSet("dbo.spr_UPDATE_CandadoPrograma", candado, this.Session["connection"].ToString());

                    var args = new CustomEventArgs {
                        success = true, message = GetLocalResourceObject("SiCambios").ToString()                              /*"Cambios realizados"*/
                    };
                    ResponseControlEventHandler(sender, args);

                    //popUpMessageControl1.setAndShowInfoMessage("Cambios realizados.", Common.MESSAGE_TYPE.Success);
                }
            }
            catch (Exception ex)
            {
                popUpMessageControl1.setAndShowInfoMessage(GetLocalResourceObject("NoCambios").ToString(), Common.MESSAGE_TYPE.Warning);
                log.Error(ex);
            }
        }
    }
Ejemplo n.º 56
0
        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType == DataControlRowType.Header)
                {
                    e.Row.Cells[0].Text = "游戏战区/时间";
                    for (int i = 1; i < e.Row.Cells.Count; i++)
                    {
                        DateTime date = new DateTime();
                        if (DateTime.TryParse(e.Row.Cells[i].Text, out date))
                        {
                            e.Row.Cells[i].Text = date.ToString("yyyy-MM-dd");//改变时间格式
                        }
                    }
                }
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    e.Row.Cells[0].Text = GetTypeNameT(DropDownListArea2, e.Row.Cells[0].Text);//通过战区ID显示战区名称
                    e.Row.Attributes.Add("onMouseOver", "SetNewColor(this);");
                    e.Row.Attributes.Add("onMouseOut", "SetOldColor(this)");

                    if (e.Row.RowIndex == 0)
                    {
                        e.Row.BackColor = color1;
                    }
                    else if (e.Row.Cells[0].Text == GridView1.Rows[e.Row.RowIndex - 1].Cells[0].Text)
                    {
                        e.Row.BackColor = GridView1.Rows[e.Row.RowIndex - 1].BackColor;
                    }
                    else
                    {
                        e.Row.BackColor = GridView1.Rows[e.Row.RowIndex - 1].BackColor == color1 ? color2 : color1;
                    }

                    for (int i = 1; i < e.Row.Cells.Count; i++)
                    {
                        int num = Convert.ToInt32(e.Row.Cells[i].Text.Replace(",", ""));
                        if (dicSum.ContainsKey(i))
                        {
                            dicSum[i] += num;
                        }
                        else
                        {
                            dicSum.Add(i, num);
                        }
                    }
                }
                else if (e.Row.RowType == DataControlRowType.Footer)
                {
                    e.Row.Cells[0].Text = App_GlobalResources.Language.LblSum;

                    for (int i = 1; i < e.Row.Cells.Count; i++)
                    {
                        e.Row.Cells[i].Text = dicSum[i].ToString("#,#0");
                    }
                }
            }
            catch (System.Exception ex)
            {
            }
        }
Ejemplo n.º 57
0
        private static ResultTable ExecuteRelatedInternal(SqlBuilder builder, Dictionary <string, RowData> results)
        {
            if (results.Count > 0)
            {
                MetadataTable mt = builder.BaseTable().WithMetadata().Model;
                foreach (string key in results.Keys)
                {
                    foreach (MetadataForeignKey fk in mt.ForeignKeys.Values.Where(x => (x.ReferencedSchema + "." + x.ReferencedTable).Equals(key, StringComparison.OrdinalIgnoreCase)))
                    {
                        RowData row = results[key];
                        foreach (MetadataColumnReference mcr in fk.ColumnReferences)
                        {
                            if (row.Columns.Contains(mcr.Column.Name))
                            {
                                Field f = builder.BaseTable().FindField(mcr.Column.Name);
                                if (f != null)
                                {
                                    f.Value = row.Column(mcr.Column.Name);
                                }
                                else
                                {
                                    (builder.BaseTable() as InsertIntoTable).Value(mcr.Column.Name, row.Column(mcr.Column.Name), SqlDbType.VarChar);
                                }
                            }
                        }
                    }
                }
            }
            DataTable   dt    = new DataTable();
            ResultTable table = new ResultTable();

            using (SqlConnection context = new SqlConnection(builder.ConnectionString))
            {
                context.Open();
                SqlCommand     cmd     = new SqlCommand(builder.ToSql(), context);
                SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                adapter.AcceptChangesDuringFill = false;
                adapter.Fill(dt);
                context.Close();
            }

            if (builder.SubQueries.Count > 0)
            {
                Dictionary <string, RowData> subresults = new System.Collections.Generic.Dictionary <string, RowData>(results);
                if (dt.Rows.Count > 0)
                {
                    MetadataTable mt = builder.BaseTable().WithMetadata().Model;
                    if (!subresults.ContainsKey(mt.Fullname))
                    {
                        ResultTable rt  = new ResultTable(dt, ResultTable.DateHandlingEnum.None);
                        RowData     row = rt.First();
                        table.Add(row);
                        subresults.Add(mt.Fullname, row);
                    }
                }
                foreach (SqlBuilder Builder in builder.SubQueries.Values)
                {
                    ResultTable sub = ExecuteRelatedInternal(Builder, subresults);
                    foreach (RowData row in sub)
                    {
                        table.Add(row);
                    }
                }
            }
            return(table);
        }
Ejemplo n.º 58
0
        private void appendDeviceNode(TreeNode gpNode, GroupInfo foundGroup, long lastSelectedGpID, ref TreeNode willSelectedNode)
        {
            System.Collections.Generic.Dictionary <string, string> dictionary = new System.Collections.Generic.Dictionary <string, string>();
            string groupType;

            switch (groupType = foundGroup.GroupType)
            {
            case "zone":
                if (foundGroup.GetMemberList() != null && foundGroup.GetMemberList().Length > 0)
                {
                    string text = ClientAPI.getRacklistByZonelist(foundGroup.GetMemberList());
                    text = commUtil.uniqueIDs(text);
                    if (text.Length > 0)
                    {
                        text = text.Substring(0, text.Length - 1);
                        DataRow[] dataRows = ClientAPI.getDataRows(0, "rack_id in (" + text + ")", "");
                        DataRow[] array    = dataRows;
                        for (int i = 0; i < array.Length; i++)
                        {
                            DataRow dataRow = array[i];
                            dictionary.Add(dataRow["device_id"].ToString(), "");
                        }
                    }
                }
                break;

            case "rack":
            case "allrack":
                if (foundGroup.GetMemberList() != null && foundGroup.GetMemberList().Length > 0)
                {
                    DataRow[] dataRows = ClientAPI.getDataRows(0, "rack_id in (" + foundGroup.GetMemberList() + ")", "");
                    DataRow[] array2   = dataRows;
                    for (int j = 0; j < array2.Length; j++)
                    {
                        DataRow dataRow2 = array2[j];
                        dictionary.Add(dataRow2["device_id"].ToString(), "");
                    }
                }
                break;

            case "dev":
            case "alldev":
                if (foundGroup.GetMemberList() != null && foundGroup.GetMemberList().Length > 0)
                {
                    string[] array3 = foundGroup.GetMemberList().Split(new string[]
                    {
                        ","
                    }, System.StringSplitOptions.RemoveEmptyEntries);
                    string[] array4 = array3;
                    for (int k = 0; k < array4.Length; k++)
                    {
                        string key = array4[k];
                        dictionary.Add(key, "");
                    }
                }
                break;

            case "outlet":
            case "alloutlet":
            {
                new System.Collections.Generic.Dictionary <string, string>();
                DataSet dataSet = ClientAPI.getDataSet(0);
                if (dataSet == null)
                {
                    return;
                }
                if (foundGroup.GetMemberList() != null && foundGroup.GetMemberList().Length != 0)
                {
                    DataTable dataTable = dataSet.Tables[2];
                    string[]  array5    = foundGroup.GetMemberList().Split(new string[]
                        {
                            ","
                        }, System.StringSplitOptions.RemoveEmptyEntries);
                    System.Collections.Generic.Dictionary <string, string> dictionary2 = new System.Collections.Generic.Dictionary <string, string>();
                    string[] array6 = array5;
                    for (int l = 0; l < array6.Length; l++)
                    {
                        string text2 = array6[l];
                        dictionary2.Add(text2, text2);
                    }
                    foreach (DataRow dataRow3 in dataTable.Rows)
                    {
                        string text3 = System.Convert.ToString(dataRow3["port_id"]);
                        if (dictionary2.ContainsKey(text3))
                        {
                            string key2 = dataRow3["device_id"].ToString();
                            if (dictionary.ContainsKey(key2))
                            {
                                string text4 = dictionary[key2];
                                text4            = text4 + "," + text3;
                                dictionary[key2] = text4;
                            }
                            else
                            {
                                dictionary.Add(key2, text3);
                            }
                        }
                    }
                }
                break;
            }
            }
            DataRow[] dataRows2 = ClientAPI.getDataRows(0, "", "device_nm ASC");
            DataRow[] array7    = dataRows2;
            for (int m = 0; m < array7.Length; m++)
            {
                DataRow dataRow4 = array7[m];
                string  text5    = System.Convert.ToString(dataRow4["device_id"]);
                if (dictionary.ContainsKey(text5))
                {
                    long     num2     = System.Convert.ToInt64(text5);
                    string   text6    = (string)dataRow4["device_nm"];
                    TreeNode treeNode = new TreeNode();
                    treeNode.Text = text6;
                    treeNode.Tag  = text5 + "@" + dictionary[text5];
                    if (!ClientAPI.IsDeviceOnline(System.Convert.ToInt32(text5)))
                    {
                        treeNode.ImageIndex         = 2;
                        treeNode.SelectedImageIndex = 2;
                    }
                    else
                    {
                        treeNode.ImageIndex         = 3;
                        treeNode.SelectedImageIndex = 3;
                    }
                    gpNode.Nodes.Add(treeNode);
                    if (lastSelectedGpID == num2)
                    {
                        willSelectedNode = treeNode;
                    }
                }
            }
        }
    public void LoadLevel()
    {
        int verticalOffset = 85;

        Debug.Log("About to load level folder: " + _fullMapPath + ".");

        Substrate.AnvilWorld mcWorld = Substrate.AnvilWorld.Create(_fullMapPath);

        Substrate.AnvilRegionManager mcAnvilRegionManager = mcWorld.GetRegionManager();

        OpenCog.BlockSet.OCBlockSet blockSet = _map.GetBlockSet();

        //_map.GetSunLightmap().SetSunHeight(20, 4, 4);

        int createCount = 0;

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

        //Debug.Log("In LoadLevel, there are " + blockSet.BlockCount + " blocks available.");

        foreach (Substrate.AnvilRegion mcAnvilRegion in mcAnvilRegionManager)
        {
            // Loop through x-axis of chunks in this region
            for (int iMCChunkX = 0; iMCChunkX < mcAnvilRegion.XDim; iMCChunkX++)
            {
                // Loop through z-axis of chunks in this region.
                for (int iMCChunkZ = 0; iMCChunkZ < mcAnvilRegion.ZDim; iMCChunkZ++)
                {
                    // Retrieve the chunk at the current position in our 2D loop...
                    Substrate.ChunkRef mcChunkRef = mcAnvilRegion.GetChunkRef(iMCChunkX, iMCChunkZ);

                    if (mcChunkRef != null)
                    {
                        if (mcChunkRef.IsTerrainPopulated)
                        {
                            // Ok...now to stick the blocks in...

                            int iMCChunkY = 0;

                            OCChunk chunk     = null;                        //new OCChunk(_map, new Vector3i(iMCChunkX, iMCChunkY, iMCChunkZ));
                            OCChunk lastChunk = null;


                            Vector3i chunkPos     = new Vector3i(mcAnvilRegion.ChunkGlobalX(iMCChunkX), iMCChunkY + verticalOffset, mcAnvilRegion.ChunkGlobalZ(iMCChunkZ));
                            Vector3i lastChunkPos = Vector3i.zero;
                            chunk = _map.GetChunkInstance(chunkPos);

                            for (int iMCChunkInternalY = 0; iMCChunkInternalY < mcChunkRef.Blocks.YDim; iMCChunkInternalY++)
                            {
                                if (iMCChunkInternalY / OCChunk.SIZE_Y > iMCChunkY)
                                {
                                    lastChunk    = chunk;
                                    lastChunkPos = chunkPos;
                                    chunkPos     = new Vector3i(mcAnvilRegion.ChunkGlobalX(iMCChunkX), (iMCChunkInternalY + verticalOffset) / OCChunk.SIZE_Y, mcAnvilRegion.ChunkGlobalZ(iMCChunkZ));
                                    chunk        = _map.GetChunkInstance(chunkPos);
                                }

                                for (int iMCChunkInternalX = 0; iMCChunkInternalX < mcChunkRef.Blocks.XDim; iMCChunkInternalX++)
                                {
                                    for (int iMCChunkInternalZ = 0; iMCChunkInternalZ < mcChunkRef.Blocks.ZDim; iMCChunkInternalZ++)
                                    {
                                        int iBlockID = mcChunkRef.Blocks.GetID(iMCChunkInternalX, iMCChunkInternalY, iMCChunkInternalZ);

                                        if (iBlockID != 0)
                                        {
                                            Vector3i blockPos = new Vector3i(iMCChunkInternalX, iMCChunkInternalY % OCChunk.SIZE_Y, iMCChunkInternalZ);

                                            int ourBlockID = -1;

//											switch (iBlockID)
//											{
//											case 3: // Dirt to first grass
//												ourBlockID = 1;
//												break;
//											case 12: // Grass to grass
//												ourBlockID = 1;
//												break;
//											case 13: // Gravel to stone
//												ourBlockID = 4;
//												break;
//											case 1: // Stone to second stone
//												ourBlockID = 5;
//												break;
//											case 16: // Coal ore to fungus
//												ourBlockID = 17;
//												break;
//											case 15: // Iron ore to pumpkin
//												ourBlockID = 20;
//												break;
//											case 9: // Water to water
//												ourBlockID = 8;
//												//Debug.Log ("Creating some water at [" + blockPos.x + ", " + blockPos.y + ", " + blockPos.z + "]");
//												break;
////											case 2:
////												iBlockID = 16;
////												break;
////											case 4:
////												iBlockID = 16;
////												break;
////											case 18:
////												iBlockID = 16;
////												break;
//											default:
//											{
//												//Debug.Log ("Unmapped BlockID: " + iBlockID);
//
//												if (!unmappedBlockTypes.ContainsKey (iBlockID))
//												{
//													unmappedBlockTypes.Add (iBlockID, 1);
//												}
//												else
//												{
//													unmappedBlockTypes[iBlockID] += 1;
//												}
//
//												break;
//												}
//											}

                                            if (mcToOCBlockDictionary.ContainsKey(iBlockID))
                                            {
                                                ourBlockID = mcToOCBlockDictionary[iBlockID];
                                            }
                                            else
                                            {
                                                if (!unmappedBlockTypes.ContainsKey(iBlockID))
                                                {
                                                    unmappedBlockTypes.Add(iBlockID, 1);
                                                }
                                                else
                                                {
                                                    unmappedBlockTypes[iBlockID] += 1;
                                                }
                                            }

                                            if (ourBlockID != -1)
                                            {
                                                OpenCog.BlockSet.BaseBlockSet.OCBlock newBlock = blockSet.GetBlock(ourBlockID);

                                                OCBlockData block = new OpenCog.Map.OCBlockData(newBlock, blockPos);

                                                chunk.SetBlock(block, blockPos);
                                                OpenCog.Map.Lighting.OCLightComputer.RecomputeLightAtPosition(_map, blockPos);

                                                if (block.block.GetName() == "Battery")
                                                {
                                                    GameObject batteryPrefab = OCMap.Instance.BatteryPrefab;
                                                    if (batteryPrefab == null)
                                                    {
                                                        UnityEngine.Debug.Log("OCBuilder::Update, batteryPrefab == null");
                                                    }
                                                    else
                                                    {
                                                        GameObject battery = (GameObject)GameObject.Instantiate(batteryPrefab);
                                                        battery.transform.position = blockPos;
                                                        battery.name             = "Battery";
                                                        battery.transform.parent = OCMap.Instance.BatteriesSceneObject.transform;
                                                    }
                                                }

                                                if (block.block.GetName() == "Hearth")
                                                {
                                                    GameObject hearthPrefab = OCMap.Instance.HearthPrefab;
                                                    if (hearthPrefab == null)
                                                    {
                                                        UnityEngine.Debug.Log("OCBuilder::Update, hearthPrefab == null");
                                                    }
                                                    else
                                                    {
                                                        GameObject hearth = (GameObject)GameObject.Instantiate(hearthPrefab);
                                                        hearth.transform.position = blockPos;
                                                        hearth.name             = "Hearth";
                                                        hearth.transform.parent = OCMap.Instance.HearthsSceneObject.transform;
                                                    }
                                                }

                                                createCount += 1;
                                            }
                                        }
                                    }                             // End for (int iMCChunkInternalZ = 0; iMCChunkInternalZ < mcChunkRef.Blocks.ZDim; iMCChunkInternalZ++)
                                }                                 // End for (int iMCChunkInternalY = 0; iMCChunkInternalY < mcChunkRef.Blocks.YDim; iMCChunkInternalY++)

                                string chunkCoord = chunkPos.x + ", " + chunkPos.z;

                                if (!chunkList.ContainsKey(chunkCoord))
                                {
                                    chunkList.Add(chunkCoord, chunkPos);
                                }

                                if (iMCChunkY < iMCChunkInternalY / OCChunk.SIZE_Y)
                                {
                                    _map.Chunks.AddOrReplace(lastChunk, lastChunkPos);
                                    _map.UpdateChunkLimits(lastChunkPos);
                                    _map.SetDirty(lastChunkPos);
                                    iMCChunkY = iMCChunkInternalY / OCChunk.SIZE_Y;
                                }
                            } // End for (int iMCChunkInternalX = 0; iMCChunkInternalX < mcChunkRef.Blocks.XDim; iMCChunkInternalX++)
                        }     // End if (mcChunkRef.IsTerrainPopulated)
                    }         // End if (mcChunkRef != null)
                }             // End for (int iMCChunkZ = 0; iMCChunkZ < mcAnvilRegion.ZDim; iMCChunkZ++)
            }                 // End for (int iMCChunkX  = 0; iMCChunkX < mcAnvilRegion.XDim; iMCChunkX++)
        }                     // End foreach( Substrate.AnvilRegion mcAnvilRegion in mcAnvilRegionManager )

        foreach (Vector3i chunkToLight in chunkList.Values)
        {
            OpenCog.Map.Lighting.OCChunkSunLightComputer.ComputeRays(_map, chunkToLight.x, chunkToLight.z);
            OpenCog.Map.Lighting.OCChunkSunLightComputer.Scatter(_map, null, chunkToLight.x, chunkToLight.z);
        }

        foreach (System.Collections.Generic.KeyValuePair <int, int> unmappedBlockData in unmappedBlockTypes)
        {
            UnityEngine.Debug.Log("Unmapped BlockID '" + unmappedBlockData.Key + "' found " + unmappedBlockData.Value + " times.");
        }

        Debug.Log("Loaded level: " + _fullMapPath + ", created " + createCount + " blocks.");

        _map.AddColliders();
    }     // End public void LoadLevel()
Ejemplo n.º 60
0
        internal void GetIndices(ref RectangleF rect, List <int> indices, System.Collections.Generic.Dictionary <int, int> foundIndicies, float maximumFeatureSize)
        {
            if (children != null)
            {
                //check each child bounds
                if (children[TL].Bounds.IntersectsWith(rect))
                {
                    children[TL].GetIndices(ref rect, indices, foundIndicies, maximumFeatureSize);
                }
                if (children[TR].Bounds.IntersectsWith(rect))
                {
                    children[TR].GetIndices(ref rect, indices, foundIndicies, maximumFeatureSize);
                }
                if (children[BL].Bounds.IntersectsWith(rect))
                {
                    children[BL].GetIndices(ref rect, indices, foundIndicies, maximumFeatureSize);
                }
                if (children[BR].Bounds.IntersectsWith(rect))
                {
                    children[BR].GetIndices(ref rect, indices, foundIndicies, maximumFeatureSize);
                }
            }
            else
            {
                if (indexList != null)
                {
                    RectangleF e1, e2 = new RectangleF();

                    //assumes already checked node's Bounds intersect rect
                    //add the node'x indices, checking if it has already been added
                    //We need to check for duplicates as a shape may intersect more than 1 node
                    for (int n = indexList.Count - 1; n >= 0; --n)
                    {
                        var i = indexList[n];
                        if (maximumFeatureSize != 0)
                        {
                            if (!tree.isPointData)
                            {
                                var b = boundsList[n];
                                if (b.Width < maximumFeatureSize && b.Height < maximumFeatureSize)
                                {
                                    continue;
                                }
                            }
                            else // points
                            {
                                e1 = boundsList[n];

                                if (n != indexList.Count - 1)
                                {
                                    if (Math.Abs(e1.X - e2.X) < maximumFeatureSize && Math.Abs(e1.Y - e2.Y) < maximumFeatureSize)
                                    {
                                        continue;
                                    }
                                }

                                e2 = e1;
                            }
                        }

                        if (!boundsList[n].IntersectsWith(rect))
                        {
                            continue;
                        }

                        if (!foundIndicies.ContainsKey(i))
                        {
                            indices.Add(i);
                            foundIndicies.Add(i, 0);
                        }
                    }
                }
            }
        }