public static string Export(Replay replay)
 {
     Game game = new Game(replay);
     GameState oldState = null;
     List<GameAction> actions = new List<GameAction>();
     for (int i = 0; i < replay.Actions.Count; i++)
     {
         if (replay.Actions[i] is ReplayTimeAction)
             actions.Add(replay.Actions[i]);
         game.Seek(i);
         List<GameAction> newActions = StateDelta.Delta(oldState, game.State);
         actions.AddRange(newActions);
         if (game.State != null)
             oldState = game.State.Clone();
     }
     List<JObject> jActions = new List<JObject>();
     TimeSpan time = TimeSpan.Zero;
     foreach (var action in actions)
     {
         if (action is ReplayTimeAction)
             time = ((ReplayTimeAction)action).Time;
         else
             jActions.Add(SerializeAction(action, time));
     }
     JObject json = new JObject(new JProperty("changes", new JArray(jActions)));
     return json.ToString(Newtonsoft.Json.Formatting.None);
 }
    public void Open(OpenCallback callback)
    {
      if(IsOpen == false)
      {
        fDataSources = new List<InterfaceDataSource>();

        if(fTwain.Open())
        {
          fDataSources.AddRange(fTwain.GetDataSources());
        }
        if(fWia.Open())
        {
          fDataSources.AddRange(fWia.GetDataSources());
        }

        foreach(InterfaceDataSource ds in fDataSources)
        {
          ds.OnNewPictureData += fActiveDataSource_OnNewPictureData;
          ds.OnScanningComplete += fActiveDataSource_OnScanningComplete;
        }
      }

      if(callback != null)
      {
        callback(IsOpen);
      }
    }
        public List<RoleAuthorization> GetDescendants(int functionId)
        {
            List<RoleAuthorization> resultList = new List<RoleAuthorization>();
            List<RoleAuthorization> childList = AuthList.FindAll(t => t.ParentId == functionId);
            resultList.AddRange(childList);

            foreach (var item in childList)
            {
                var theChildList = GetDescendants(item.FunctionId);
                resultList.AddRange(theChildList);
            }

            return resultList;
        }
 public static List<AModel> GetHotNews()
 {
     List<AModel> allHot = new List<AModel>();
     XmlDocument xmlDoc = new XmlDocument();
     xmlDoc.Load(System.AppDomain.CurrentDomain.BaseDirectory + @"\Config\websiteConfig.xml");
     XmlNode root = xmlDoc.SelectSingleNode("websites");
     foreach (XmlNode node in root.ChildNodes)
     {
         websiteModel model = new websiteModel();
         model.Name = node.Attributes[0].Value;
         model.Url = node.Attributes[1].Value;
         model.Charset = node.Attributes[2].Value;
         XmlNode foumRoot = node.SelectSingleNode("forums");
         foreach (XmlNode forumNode in foumRoot.ChildNodes)
         {
             forumModel forummodel = new forumModel();
             forummodel.Name = forumNode.Attributes[0].Value;
             forummodel.BeginFlag = forumNode.Attributes[1].Value;
             forummodel.EndFlag = forumNode.Attributes[2].Value;
             model.ForumDic.Add(forummodel.Name, forummodel);
         }
         Website website = new Website(model.Url);
         string forumContent = Forum.GetForum(website.GetWebContent(model.Charset) , model.ForumDic["头条"]);
         allHot.AddRange(A.FindAll(forumContent, model.Name));
     }
     return allHot;
 }
Example #5
0
 public List<District> getDistrictsList()
 {
     List<District> list = new List<District>();
     list.Add(new District() { Id=-1, Name="[Select District]"});
     list.AddRange(uOW.DistrictRepo.Get());
     return list;
 }
Example #6
0
		private static void Main(string[] args)
		{
			if (args.Length != 1)
			{
				Console.WriteLine("Usage: Importer [directory to process]");
				return;
			}
			string directory = args[0];
			if (!Directory.Exists(directory))
			{
				Console.WriteLine("{0} does not exists", directory);
				return;
			}
			Dictionary<Guid, Post> posts = new Dictionary<Guid, Post>();
			IDictionary<string, Category> categories = new Dictionary<string, Category>();
			List<Comment> comments = new List<Comment>();
			AddPosts(categories, directory, posts);
			foreach (string file in Directory.GetFiles(directory, "*feedback*.xml"))
			{
				IList<Comment> day_comments = ProcessComments(file, posts);
				comments.AddRange(day_comments);
			}
			Console.WriteLine("Found {0} posts in {1} categories with {2} comments", posts.Count, categories.Count, comments.Count);
			SaveToDatabase(categories, posts.Values, comments);
		}
Example #7
0
 public List<ControllerAction> GetAllowContro(string userName)
 {
     List<ControllerAction> controAction = new List<ControllerAction>();
     var rolesList = _db.Users.SingleOrDefault(a => a.UserName == userName).Roles.ToList();
     for (int i = 0; i < rolesList.Count; i++)
     {
         controAction.AddRange(rolesList[i].ControllerActions);
     }
     return controAction;
 }
        public static PhotosetsResponse GetPhotosetsResponseFromDictionary(this Dictionary<string, object> dictionary) {
            var photosets = new List<Photoset>();
            IEnumerable<Dictionary<string, object>> photosetDictionary;

            if (runningOnMono) {
                var photosetListAsArrayList = (ArrayList) dictionary.GetSubValue("photosets", "photoset");
                photosetDictionary = photosetListAsArrayList.Cast<Dictionary<string, object>>();
            } else {
                var photosetListAsIEnumerable = (IEnumerable<object>) dictionary.GetSubValue("photosets", "photoset");
                photosetDictionary = photosetListAsIEnumerable.Cast<Dictionary<string, object>>();
            }

            photosets.AddRange(photosetDictionary.Select(BuildPhotoset));

            return new PhotosetsResponse(
                int.Parse(dictionary.GetSubValue("photosets", "page").ToString()),
                int.Parse(dictionary.GetSubValue("photosets", "pages").ToString()),
                int.Parse(dictionary.GetSubValue("photosets", "perpage").ToString()),
                int.Parse(dictionary.GetSubValue("photosets", "total").ToString()),
                photosets);
        }
        public static PhotosResponse GetPhotosResponseFromDictionary(this Dictionary<string, object> dictionary, bool isAlbum) {
            var apiresponseCollectionName = isAlbum ? "photoset" : "photos";
            var photos = new List<Photo>();
            IEnumerable<Dictionary<string, object>> photoDictionary;

            if (runningOnMono) {
                var photoListAsArrayList = (ArrayList) dictionary.GetSubValue(apiresponseCollectionName, "photo");
                photoDictionary = photoListAsArrayList.Cast<Dictionary<string, object>>();
            } else {
                var photoListAsIEnumerable = (IEnumerable<object>) dictionary.GetSubValue(apiresponseCollectionName, "photo");
                photoDictionary = photoListAsIEnumerable.Cast<Dictionary<string, object>>();
            }

            photos.AddRange(photoDictionary.Select(BuildPhoto));

            return new PhotosResponse(
                int.Parse(dictionary.GetSubValue(apiresponseCollectionName, "page").ToString()),
                int.Parse(dictionary.GetSubValue(apiresponseCollectionName, "pages").ToString()),
                int.Parse(dictionary.GetSubValue(apiresponseCollectionName, "perpage").ToString()),
                int.Parse(dictionary.GetSubValue(apiresponseCollectionName, "total").ToString()),
                photos);
        }
        void UCCustomerAddOrEdit_SaveEvent(object sender, EventArgs e)  //数据保存
        {
            try
            {
                if (!CheckControlValue()) return;
                var sysSqlStrList = new List<SysSQLString>();
                
                var custSql = BuildCustomerSqlString();
                sysSqlStrList.Add(custSql.Item1);
                sysSqlStrList.AddRange(BuildContactRelation(custSql.Item2));
                sysSqlStrList.AddRange(BuildVehicleRelation(custSql.Item2));
                sysSqlStrList.AddRange(BuildVipMemberSqlString(custSql.Item2));

                //ucAttr.GetAttachmentSql(sysSqlStrList);   //保存附件时失败...目前保留此代码
                var opName = wStatus == WindowStatus.Edit ? "更新客户档案" : "新增客户档案";
                var result = DBHelper.BatchExeSQLStringMultiByTrans(opName, sysSqlStrList);
                if (result)
                {
                    var customer = new tb_customer();
                    customer.cust_id = custSql.Item1.Param["cust_id"];
                    customer.cust_code = custSql.Item1.Param["cust_code"];
                    customer.cust_name = custSql.Item1.Param["cust_name"];
                    customer.cust_short_name = custSql.Item1.Param["cust_short_name"];
                    customer.cust_quick_code = custSql.Item1.Param["cust_quick_code"];
                    customer.cust_type = custSql.Item1.Param["cust_type"];
                    customer.legal_person = custSql.Item1.Param["legal_person"];
                    customer.enterprise_nature = custSql.Item1.Param["enterprise_nature"];
                    customer.cust_tel = custSql.Item1.Param["cust_tel"];
                    customer.cust_fax = custSql.Item1.Param["cust_fax"];
                    customer.cust_email = custSql.Item1.Param["cust_email"];
                    customer.cust_phone = custSql.Item1.Param["cust_phone"];
                    customer.cust_website = custSql.Item1.Param["cust_website"];
                    customer.province = custSql.Item1.Param["province"];
                    customer.city = custSql.Item1.Param["city"];
                    customer.county = custSql.Item1.Param["county"];
                    customer.cust_address = custSql.Item1.Param["cust_address"];
                    customer.zip_code = custSql.Item1.Param["zip_code"];
                    customer.tax_num = custSql.Item1.Param["tax_num"];
                    customer.indepen_legalperson = custSql.Item1.Param["indepen_legalperson"];
                    customer.credit_rating = custSql.Item1.Param["credit_rating"];
                    customer.credit_line = Convert.ToInt32(custSql.Item1.Param["credit_line"]);
                    customer.credit_account_period = Convert.ToInt32(custSql.Item1.Param["credit_account_period"]);
                    customer.price_type = custSql.Item1.Param["price_type"];
                    customer.billing_name = custSql.Item1.Param["billing_name"];
                    customer.billing_address = custSql.Item1.Param["billing_address"];
                    customer.billing_account = custSql.Item1.Param["billing_account"];
                    customer.open_bank = custSql.Item1.Param["open_bank"];
                    customer.bank_account = custSql.Item1.Param["bank_account"];
                    customer.bank_account_person = custSql.Item1.Param["bank_account_person"];
                    customer.cust_remark = custSql.Item1.Param["cust_remark"];
                    customer.is_member = custSql.Item1.Param["is_member"];
                    customer.member_number = custSql.Item1.Param["member_number"];
                    customer.member_class = custSql.Item1.Param["member_class"];
                    if(rdbis_member_y.Checked) customer.member_period_validity = Convert.ToInt64(custSql.Item1.Param["member_period_validity"]);
                    customer.status = custSql.Item1.Param["status"];
                    customer.enable_flag = custSql.Item1.Param["enable_flag"];
                    customer.data_source = custSql.Item1.Param["data_source"];
                    customer.cust_crm_guid = custSql.Item1.Param["cust_crm_guid"];

                    customer.accessories_discount = 0;
                    customer.workhours_discount = 0;
                    customer.country = custSql.Item1.Param["country"];
                    customer.indepen_legalperson = custSql.Item1.Param["indepen_legalperson"];
                    customer.market_segment = custSql.Item1.Param["market_segment"];
                    customer.institution_code = custSql.Item1.Param["institution_code"];
                    customer.com_constitution = custSql.Item1.Param["com_constitution"];
                    customer.registered_capital = custSql.Item1.Param["registered_capital"];
                    customer.vehicle_structure = custSql.Item1.Param["vehicle_structure"];
                    customer.agency = custSql.Item1.Param["agency"];
                    customer.sap_code = custSql.Item1.Param["sap_code"];
                    customer.business_scope = custSql.Item1.Param["business_scope"];
                    customer.ent_qualification = custSql.Item1.Param["ent_qualification"];

                    
                    if (wStatus == WindowStatus.Edit)
                    {
                        customer.update_by = custSql.Item1.Param["update_by"];
                        customer.update_time = Convert.ToInt64(custSql.Item1.Param["update_time"]);
                    }
                    else
                    {
                        customer.create_time = Convert.ToInt64(custSql.Item1.Param["create_time"]);
                        customer.create_by = custSql.Item1.Param["create_by"];
                    }
                    var flag = DBHelper.WebServHandler(opName, EnumWebServFunName.UpLoadCustomer, customer);
                    if (String.IsNullOrEmpty(flag))
                    {
                        var contactSql = BuildContactRelation(custSql.Item2).ToArray();
                        foreach (var sysSqlString in contactSql)
                        {
                            if (!sysSqlString.Param.ContainsKey("cont_id")) continue;
                            var contId = sysSqlString.Param["cont_id"];
                            var dt1 = DBHelper.GetTable("获取客户CRMID", "tb_customer","*", String.Format("cust_id = '{0}'", customer.cust_id), "", "");
                            var dt = DBHelper.GetTable("根据客户档案获取联系信息", "v_contacts", string.Format("*,{0} phone", EncryptByDB.GetDesFieldValue("cont_phone")), " cont_id = '" + contId + "'", "", "");
                            if (dt.DefaultView != null && dt.DefaultView.Count > 0)
                            {
                                var cont = new tb_contacts_ex
                                {
                                    cont_id = CommonCtrl.IsNullToString(dt.DefaultView[0]["cont_id"]),
                                    cont_name = CommonCtrl.IsNullToString(dt.DefaultView[0]["cont_name"]),
                                    cont_post = CommonCtrl.IsNullToString(dt.DefaultView[0]["cont_post_name"]),
                                    cont_phone = CommonCtrl.IsNullToString(dt.DefaultView[0]["phone"]),
                                    nation = CommonCtrl.IsNullToString(dt.DefaultView[0]["nation_name"]),
                                    parent_customer = CommonCtrl.IsNullToString(dt1.DefaultView[0]["cust_crm_guid"]),
                                    sex = CommonCtrl.IsNullToString(dt.DefaultView[0]["sex"]),
                                    status = CommonCtrl.IsNullToString(dt.DefaultView[0]["status"]),
                                    cont_post_remark = CommonCtrl.IsNullToString(dt.DefaultView[0]["post_remark"]),
                                    cont_crm_guid = CommonCtrl.IsNullToString(dt.DefaultView[0]["cont_crm_guid"]),
                                    contact_type = "01" //标识类型为联系人
                                };
                                var flag4Cont = DBHelper.WebServHandler(opName, EnumWebServFunName.UpLoadCcontact, cont);
                                if (String.IsNullOrEmpty(flag4Cont))
                                {
                                    //do something
                                }
                            }
                            
                        }
                        
                    }
                    MessageBoxEx.Show("保存成功!", "保存");
                    UCCustomerManager.BindPageData();
                    deleteMenuByTag(Tag.ToString(), UCCustomerManager.Name);
                }
                else
                {
                    MessageBoxEx.Show("保存失败!", "保存");
                }
            }
            catch (Exception ex)
            {
                MessageBoxEx.Show("保存失败!" + ex.Message, "提示");
            }

        }
        private IEnumerable<Node> GetAffectedMembers(
            IList<PathFilterExpression> pathTree, 
            ref int lastPosition,
            Node node)
        {
            for (int i = lastPosition; i < pathTree.Count; i++)
            {
                // seems absurd, but this MAY be called recursively, OR simply
                // iterated via the for loop
                lastPosition = i; 
                
                var jsonContract = (JsonObjectContract)_ContractResolver.ResolveContract(node.Target.GetType());
                var attemptedProperty = jsonContract.Properties.GetClosestMatchProperty(pathTree[i].Path);
                if (attemptedProperty == null)
                {
                    if (!_ServerConfiguration.ResourceExtensionExists(pathTree[i].Path))
                    {
                        // property cannot be found, and we're not working with an extension.
                        ErrorType = ScimErrorType.InvalidPath;
                        break;
                    }

                    // this is a resource extension
                    // TODO: (DG) the code below works as well and will remove once it's determined how 
                    // repositories will access and persist extension data.  Currently, Extensions property is public.
//                    var memberInfo = node.Target.GetType().GetProperty("Extensions", BindingFlags.NonPublic | BindingFlags.Instance);
//                    var property = new JsonProperty
//                    {
//                        PropertyType = memberInfo.PropertyType,
//                        DeclaringType = memberInfo.DeclaringType,
//                        ValueProvider = new ReflectionValueProvider(memberInfo),
//                        AttributeProvider = new ReflectionAttributeProvider(memberInfo),
//                        Readable = true,
//                        Writable = true,
//                        ShouldSerialize = member => false
//                    };

                    attemptedProperty = jsonContract.Properties.GetProperty("extensions", StringComparison.Ordinal);
                }

                // if there's nothing to filter and we're not yet at the last path entry, continue
                if (pathTree[i].Filter == null && i != pathTree.Count - 1)
                {
                    // if they enter an invalid target 
                    if (attemptedProperty.PropertyType.IsTerminalObject())
                    {
                        ErrorType = ScimErrorType.InvalidPath;
                        break;
                    }

                    object targetValue;
                    var propertyType = attemptedProperty.PropertyType;

                    // support for resource extensions
                    if (propertyType == typeof (ResourceExtensions))
                    {
                        var resourceExtensions = (ResourceExtensions) attemptedProperty.ValueProvider.GetValue(node.Target);
                        var extensionType = _ServerConfiguration.GetResourceExtensionType(node.Target.GetType(), pathTree[i].Path);
                        if (_Operation.OperationType == OperationType.Remove && !resourceExtensions.Contains(extensionType))
                            break;

                        targetValue = resourceExtensions.GetOrCreate(extensionType);
                    }
                    else
                    {
                        // if targetValue is null, then we need to initialize it, UNLESS we're in a remove operation
                        // e.g. user.name.givenName, when name == null
                        targetValue = attemptedProperty.ValueProvider.GetValue(node.Target);
                        if (targetValue == null)
                        {
                            if (_Operation.OperationType == OperationType.Remove)
                                break;

                            if (!propertyType.IsNonStringEnumerable())
                            {
                                // if just a normal complex type, just create a new instance
                                targetValue = propertyType.CreateInstance();
                            }
                            else
                            {
                                var enumerableInterface = propertyType.GetEnumerableType();
                                var listArgumentType = enumerableInterface.GetGenericArguments()[0];
                                var listType = typeof (List<>).MakeGenericType(listArgumentType);
                                targetValue = listType.CreateInstance();
                            }

                            attemptedProperty.ValueProvider.SetValue(node.Target, targetValue);
                        }
                    }

                    // the Target becomes the Target's child property value
                    // the Parent becomes the current Target
                    node = new Node(targetValue, node.Target);
                    continue; // keep traversing the path tree
                }
                    
                if (pathTree[i].Filter != null)
                {
                    // we can only filter enumerable types
                    if (!attemptedProperty.PropertyType.IsNonStringEnumerable())
                    {
                        ErrorType = ScimErrorType.InvalidFilter;
                        break;
                    }

                    var enumerable = attemptedProperty.ValueProvider.GetValue(node.Target) as IEnumerable;
                    if (enumerable == null)
                    {
                        // if the value of the attribute is null then there's nothing to filter
                        // it should never get here beause ScimObjectAdapter should apply a 
                        // different ruleset for null values; replacing or setting the attribute value
                        ErrorType = ScimErrorType.NoTarget;
                        break;
                    }
                    
                    dynamic predicate;
                    try
                    {
                        // parse our filter into an expression tree
                        var lexer = new ScimFilterLexer(new AntlrInputStream(pathTree[i].Filter));
                        var parser = new ScimFilterParser(new CommonTokenStream(lexer));

                        // create a visitor for the type of enumerable generic argument
                        var enumerableType = attemptedProperty.PropertyType.GetGenericArguments()[0];
                        var filterVisitorType = typeof (ScimFilterVisitor<>).MakeGenericType(enumerableType);
                        var filterVisitor = (IScimFilterVisitor) filterVisitorType.CreateInstance(_ServerConfiguration);
                        predicate = filterVisitor.VisitExpression(parser.parse()).Compile();
                    }
                    catch (Exception)
                    {
                        ErrorType = ScimErrorType.InvalidFilter;
                        break;
                    }

                    // we have an enumerable and a filter predicate
                    // for each element in the enumerable that satisfies the predicate, 
                    // visit that element as part of the path tree
                    var originalHasElements = false;
                    var filteredNodes = new List<Node>();
                    var enumerator = enumerable.GetEnumerator();
                    lastPosition = i + 1; // increase the position in the tree
                    while (enumerator.MoveNext())
                    {
                        originalHasElements = true;
                        dynamic currentElement = enumerator.Current;
                        if ((bool) predicate(currentElement))
                        {
                            filteredNodes.AddRange(
                                GetAffectedMembers(
                                    pathTree,
                                    ref lastPosition,
                                    new Node(enumerator.Current, node.Target)));
                        }
                    }

                    /* SCIM PATCH 'replace' RULE:
                        o  If the target location is a multi-valued attribute for which a
                            value selection filter ("valuePath") has been supplied and no
                            record match was made, the service provider SHALL indicate failure
                            by returning HTTP status code 400 and a "scimType" error code of
                            "noTarget".
                    */
                    if (originalHasElements &&
                        filteredNodes.Count == 0 &&
                        _Operation != null &&
                        _Operation.OperationType == OperationType.Replace)
                    {
                        throw new ScimPatchException(
                            ScimErrorType.NoTarget, _Operation);
                    }

                    return filteredNodes;
                }
            }

            return new List<Node> { node };
        }
Example #12
0
            //Converts the Data structure into an array of bytes.
            public byte[] ToByte()
            {
                List<byte> result = new List<byte>();

                //First four are for the Command.
                result.AddRange(BitConverter.GetBytes((int)cmdCommand));

                //Add the length of the name.
                if (strName != null)
                    result.AddRange(BitConverter.GetBytes(strName.Length));
                else
                    result.AddRange(BitConverter.GetBytes(0));

                //Add the name.
                if (strName != null)
                    result.AddRange(Encoding.UTF8.GetBytes(strName));

                return result.ToArray();
            }
Example #13
0
 private List<District> GetAllChildren(int id)
 {
     var children = new List<District>();
     var current = uOW.DistrictRepo.All.Where(d => d.Id == id).Include(d => d.Coordinates).FirstOrDefault();
     if (current.IsFolder)
     {
         var currentChildren = uOW.DistrictRepo.All.Where(d => d.ParentId == id).Include(d=>d.Coordinates).ToList();
         foreach(var child in currentChildren)
         {
             children.AddRange(GetAllChildren(child.Id));
         }
         children.Add(current);
     }
     else
     {
         children.Add(current);
     }
     return children;
 }
        /// <summary>
        /// 保存
        /// </summary>
        void UCPersonnelAddOrEdit_SaveEvent(object sender, EventArgs e)
        {
            string msg = string.Empty;
            bool bln = Validator(ref msg);
            if (!bln)
            {
                return;
            }

            string newGuid = string.Empty;
            string currUser_id = "";

            string keyName = string.Empty;
            string keyValue = string.Empty;
            string opName = "新增人员信息";
            Dictionary<string, string> dicFileds = new Dictionary<string, string>();

            dicFileds.Add("user_name", txtuser_name.Caption.Trim());//人员姓名
            //账号
            if (cbois_operator.SelectedValue.ToString() == DataSources.EnumYesNo.Yes.ToString("d"))
            {
                dicFileds.Add("land_name", txtland_name.Caption.Trim());
            }
            else
            {
                dicFileds.Add("land_name", "");
            }

            dicFileds.Add("user_phone", txtuser_phone.Caption.Trim());//手机
            dicFileds.Add("user_telephone", txtuser_telephone.Caption.Trim());//固话    
            dicFileds.Add("org_id", txcorg_name.Tag.ToString().Trim());//组织id 
            dicFileds.Add("sex", cbosex.SelectedValue.ToString());//性别
            dicFileds.Add("user_fax", txtuser_fax.Caption.Trim());//传真 
            dicFileds.Add("is_operator", cbois_operator.SelectedValue.ToString());//是否操作员 
            dicFileds.Add("idcard_type", cboidcard_type.SelectedValue.ToString());//证件类型 
            dicFileds.Add("user_email", txtuser_email.Caption.Trim());//邮箱 
            dicFileds.Add("idcard_num", txtidcard_num.Caption.Trim());//证件号码 
            dicFileds.Add("user_address", txtuser_address.Caption.Trim());//联系地址
            dicFileds.Add("remark", txtremark.Caption.Trim());//备注 
            //密码
            if (cbois_operator.SelectedValue.ToString() == DataSources.EnumYesNo.Yes.ToString("d"))
            {
                dicFileds.Add("password", txtPassWord.Caption.Trim());
            }
            else
            {
                dicFileds.Add("password", "");//密码
            }

            dicFileds.Add("nation", cbonation.SelectedValue.ToString());//民族 
            dicFileds.Add("graduate_institutions", txtgraduate_institutions.Caption.Trim());//毕业学校 
            dicFileds.Add("technical_expertise", txttechnical_expertise.Caption.Trim());//技术特长 
            dicFileds.Add("user_height", txtuser_height.Caption.Trim());//身高 
            dicFileds.Add("native_place", txtnative_place.Caption.Trim());//籍贯 
            dicFileds.Add("specialty", txtspecialty.Caption.Trim());//专业
            dicFileds.Add("entry_date", Common.LocalDateTimeToUtcLong(dtpentry_date.Value).ToString());//  入职日期 
            dicFileds.Add("user_weight", txtuser_weight.Caption.Trim());//体重 
            dicFileds.Add("register_address", txtregister_address.Caption.Trim());//户籍所在地 
            dicFileds.Add("graduate_date", Common.LocalDateTimeToUtcLong(dtpgraduate_date.Value).ToString());// 毕业时间 
            dicFileds.Add("wage", txtwage.Caption.Trim());// 工资 
            dicFileds.Add("birthday", Common.LocalDateTimeToUtcLong(dtpbirthday.Value).ToString());// 出生日期  
            dicFileds.Add("education", cboeducation.SelectedValue.ToString());//学历
            dicFileds.Add("position", cboposition.SelectedValue.ToString());//岗位
            dicFileds.Add("political_status", txtpolitical_status.Caption.Trim());//政治面貌
            dicFileds.Add("level", cbolevel.SelectedValue.ToString());//级别



            dicFileds.Add("health", cbojkzk.SelectedValue.ToString());//健康状况

            string nowUtcTicks = Common.LocalDateTimeToUtcLong(HXCPcClient.GlobalStaticObj.CurrentDateTime).ToString();
            dicFileds.Add("update_by", HXCPcClient.GlobalStaticObj.UserID);
            dicFileds.Add("update_time", nowUtcTicks);

            string crmId = string.Empty;

            if (wStatus == WindowStatus.Add || wStatus == WindowStatus.Copy)
            {
                dicFileds.Add("user_code", CommonUtility.GetNewNo(SYSModel.DataSources.EnumProjectType.User));//人员编码               

                newGuid = Guid.NewGuid().ToString();
                currUser_id = newGuid;
                dicFileds.Add("user_id", newGuid);//新ID                   
                dicFileds.Add("create_by", HXCPcClient.GlobalStaticObj.UserID);
                dicFileds.Add("create_time", nowUtcTicks);
                dicFileds.Add("enable_flag", SYSModel.DataSources.EnumEnableFlag.USING.ToString("d"));//1为未删除状态
                dicFileds.Add("status", SYSModel.DataSources.EnumStatus.Start.ToString("d"));//启用
                dicFileds.Add("data_sources", Convert.ToInt16(SYSModel.DataSources.EnumDataSources.SELFBUILD).ToString());//来源 自建
            }
            else if (wStatus == WindowStatus.Edit)
            {
                keyName = "user_id";
                keyValue = id;
                currUser_id = id;
                newGuid = id;
                crmId = dr["cont_crm_guid"].ToString();
                opName = "更新人员管理";
            }
            bln = DBHelper.Submit_AddOrEdit(opName, "sys_user", keyName, keyValue, dicFileds);

            string photo = string.Empty;
            if (picuser.Tag != null)
            {
                photo = Guid.NewGuid().ToString() + Path.GetExtension(picuser.Tag.ToString());
                if (!FileOperation.UploadFile(picuser.Tag.ToString(), photo))
                {
                    return;
                }
            }

            List<SQLObj> listSql = new List<SQLObj>();
            listSql = AddPhoto(listSql, currUser_id, photo);
            ucAttr.TableName = "sys_user";
            ucAttr.TableNameKeyValue = currUser_id;
            listSql.AddRange(ucAttr.AttachmentSql);
            DBHelper.BatchExeSQLMultiByTrans(opName, listSql);
            if (bln)
            {
                if (wStatus == WindowStatus.Add || wStatus == WindowStatus.Edit)
                {
                    var cont = new tb_contacts_ex
                           {
                               cont_id = CommonCtrl.IsNullToString(newGuid),//id
                               cont_name = CommonCtrl.IsNullToString(this.txtuser_name.Caption.Trim()),//name
                               cont_post = CommonCtrl.IsNullToString(""),//post
                               cont_phone = CommonCtrl.IsNullToString(this.txtuser_phone.Caption.Trim()),
                               nation = CommonCtrl.IsNullToString(this.cbonation.SelectedValue.ToString()),
                               parent_customer = CommonCtrl.IsNullToString(""),
                               sex = UpSex(),
                               status = CommonCtrl.IsNullToString(SYSModel.DataSources.EnumStatus.Start.ToString("d")),
                               cont_post_remark = CommonCtrl.IsNullToString(""),
                               cont_crm_guid = CommonCtrl.IsNullToString(crmId),
                               contact_type = "02"
                           };
                    Update.BeginInvoke("上传服务站工作人员", SYSModel.EnumWebServFunName.UpLoadCcontact, cont, null, null);

                    //DBHelper.WebServHandlerByFun("上传服务站工作人员", SYSModel.EnumWebServFunName.UpLoadCcontact, cont);
                }

                if (this.RefreshDataStart != null)
                {
                    this.RefreshDataStart();
                }

                LocalCache._Update(CacheList.User);

                MessageBoxEx.Show("保存成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.None);

                deleteMenuByTag(this.Tag.ToString(), this.parentName);
            }
            else
            {
                MessageBoxEx.Show("保存失败!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
Example #15
0
        private void Scan(object sender, DoWorkEventArgs args)
        {
            var repositories = Repository.MediaRepositories.Select(x => x);
            var repositoryCount = 0;
            var totalRepositories = repositories.Count();
            foreach (var repository in repositories)
            {
                var paths = new List<string>();
                var directory = new DirectoryInfo(repository.Location);
                paths.AddRange(FindFiles(directory));
                paths.AddRange(ScanSubDirectories(directory));
                repository.LastScanned = DateTime.Now;

                var pathCount = 0;
                Parallel.ForEach(paths, new ParallelOptions {MaxDegreeOfParallelism = 15}, delegate(string path)
                                            {
                                                var repo = DataAccessContext.GetRepository();
                                                pathCount += 1;
                                                ReportProgress(
                                                    CalculatePercentage(pathCount, paths.Count, repositoryCount, totalRepositories),
                                                    new RepositoryScannerState {CurrentPath = path, CurrentRepository = repository.Location});

                                                var mediaFile = repo.MediaFiles.FirstOrDefault(x => x.FullPath == path);
                                                Track track;
                                                if (mediaFile != null)
                                                {
                                                    if (mediaFile.LastModified <
                                                        (new FileInfo(mediaFile.FullPath)).LastWriteTime.AddMinutes(-1))
                                                    {
                                                        track = repo.Tracks.First(x => x.Id == mediaFile.TrackId);
                                                        //Update Track metadata
                                                        ProcessTrack(path, ref track, ref repo);
                                                        repo.SubmitChanges();
                                                    }
                                                }
                                                else
                                                {
                                                    track = new Track {Id = Guid.NewGuid()};
                                                    //Update Track metadata
                                                    ProcessTrack(path, ref track, ref repo);

                                                    repo.Tracks.InsertOnSubmit(track);
                                                    repo.SubmitChanges();

                                                    var file = new FileInfo(path);
                                                    mediaFile = new MediaFile
                                                                    {
                                                                        Id = Guid.NewGuid(),
                                                                        RepositoryId = repository.Id,
                                                                        FullPath = path,
                                                                        DateAdded = DateTime.Now,
                                                                        LastModified = file.LastWriteTime,
                                                                        FileType = file.Extension,
                                                                        Size = file.Length,
                                                                        TrackId = track.Id
                                                                    };
                                                    repo.MediaFiles.InsertOnSubmit(mediaFile);
                                                    repo.SubmitChanges();
                                                }
                                            });
                repositoryCount += 1;
            }
        }
        public int getSeriesId(string seriesName)
        {
            // TODO: A few things here.  We should add more intelligence when there is more then 1 match
            // Things like default to (US) or (UK) or what ever is usally the case.  Also, perhaps a global setting that would always take newest series first...

            if (this.IsSeriesIgnored(seriesName))
            {
                return 0;
            }

            if (this.seriesIDMapping.Keys.Contains(seriesName, StringComparer.InvariantCultureIgnoreCase))
            {
                var seriesid = this.seriesIDMapping[seriesName];
                log.DebugFormat("SD-TvDb: Direct mapping: series: {0} id: {1}", seriesName, seriesid);
                return seriesid;
            }

            if (seriesCache.Keys.Contains(seriesName, StringComparer.InvariantCultureIgnoreCase))
            {
                log.DebugFormat("SD-TvDb: Series cache hit: {0} has id: {1}", seriesName, seriesCache[seriesName]);
                return seriesCache[seriesName];
            }

            string searchSeries = seriesName;

            if (IsSeriesInMappedSeries(seriesName))
            {
                searchSeries = this.seriesNameMapping[seriesName];
            }
            else if (this.seriesNameRegex.Count > 0)
            {
                foreach (string regexEntry in seriesNameRegex.Keys)
                {
                    var regex = new Regex(regexEntry);
                    if (regex.IsMatch(seriesName))
                    {
                        if (seriesNameRegex[regexEntry].StartsWith("replace="))
                        {
                            searchSeries = regex.Replace(seriesName, seriesNameRegex[regexEntry].Substring(8));
                        }
                        else if (seriesNameRegex[regexEntry].StartsWith("id="))
                        {
                            return int.Parse(seriesNameRegex[regexEntry].Substring(3));
                        }
                        else
                        {
                            searchSeries = seriesNameRegex[regexEntry];
                        }

                        log.DebugFormat("SD-TvDb: Regex mapping: series: {0} regex: {1} seriesMatch: {2}", seriesName, regexEntry, searchSeries);
                        break;
                    }
                }
            }

            List<TvdbSearchResult> searchResults = this.tvDbService.SearchSeries(searchSeries, this.language);

            log.DebugFormat("SD-TvDb: Search for {0} return {1} results", searchSeries, searchResults.Count);

            var seriesWithoutPunctuation = Regex.Replace(searchSeries, REMOVE_PUNCTUATION, string.Empty);
            if (searchResults.Count >= 1)
            {
                for (int i = 0; i < searchResults.Count; i++)
                {
                    var sn = new List<string> { Regex.Replace(searchResults[i].SeriesName, REMOVE_PUNCTUATION, string.Empty) };
                    sn.AddRange(searchResults[i].AliasNames.Select(x => Regex.Replace(x, REMOVE_PUNCTUATION, string.Empty)));
                    if (sn.Any(x => x.Equals(seriesWithoutPunctuation, StringComparison.InvariantCultureIgnoreCase)))
                    {
                        var seriesId = searchResults[i].Id;
                        log.DebugFormat("SD-TvDb: series: {0} id: {1}", searchSeries, seriesId);
                        seriesCache.Add(seriesName, seriesId);
                        return seriesId;
                    }
                }

                log.DebugFormat("SD-TvDb: Could not find series match: {0} renamed {1}", seriesName, searchSeries);
            }

            log.DebugFormat("Cannot find series ID for {0}", seriesName);
            return 0;
        }
Example #17
0
 public IList<Model.DJ_Workers> GetTourGroupByTeId(int id)
 {
     var listTg = Idjtourgroup.GetTourGroupByTEId(id).ToList();
     var listGw = new List<Model.DJ_Group_Worker>();
     var listGw2 = new List<Model.DJ_Group_Worker>();
     List<DJ_Workers> Listdw = new List<DJ_Workers>();
     foreach (var tg in listTg)
     {
         listGw.AddRange(tg.Workers.Where(x => x.DJ_Workers.WorkerType == Model.DJ_GroupWorkerType.导游).ToList<Model.DJ_Group_Worker>());
     }
     foreach (var item in listGw)
     {
         if (listGw2.Count(x => x.DJ_Workers.IDCard == item.DJ_Workers.IDCard) == 0)
         {
             listGw2.Add(item);
         }
     }
     foreach (var item in listGw2)
     {
         Listdw.Add(item.DJ_Workers);
     }
     return Listdw;
 }
Example #18
0
        public IList<Model.DJ_Route> GetRouteByAllCondition(string groupname, string EntName, string BeginTime, string EndTime, int enterid)
        {
            IList<Model.DJ_Route> ListRoute = Idjroute.GetRouteByAllCondition(groupname, EntName, BeginTime, EndTime, enterid);
            List<Model.DJ_Route> ListWroute = new List<Model.DJ_Route>();
            if (ListRoute.Count > 1)
            {
                ListWroute.Add(ListRoute[0]);
                for (int i = 1; i < ListRoute.Count; i++)
                {
                    //过滤掉行程中重复的
                    if (ListRoute[i].DJ_TourGroup.Id == ListRoute[i - 1].DJ_TourGroup.Id && (ListRoute[i - 1].DayNo - ListRoute[i].DayNo) <= 1)
                    {
                        continue;
                    }
                    else
                    {
                        ListWroute.Add(ListRoute[i]);

                    }
                }

            }
            else
                ListWroute.AddRange(ListRoute);
            //去掉验证过的
            List<DJ_Route> ListWroute2 = new List<DJ_Route>();
            foreach (DJ_Route item in ListWroute)
            {
                if (new BLLDJConsumRecord().GetGroupConsumRecordByRouteId(item.Id) == null)
                {
                    ListWroute2.Add(item);
                }
            }
            return ListWroute2;
        }
 private static List<string> GetSynonymsForTagWords(TagProcessResult tag)
 {
     var returnList = new List<string>();
      tag.WordProcessResultList.ForEach(w => returnList.AddRange(Synonyms(w.Word)));
      return returnList;
 }
Example #20
0
 /// <summary>
 /// 获得需求天数的route
 /// </summary>
 /// <param name="MaxLiveDay">最大的天数</param>
 /// <param name="WLiveDay">需求的天数</param>
 /// <param name="ent">住宿企业</param>
 /// <param name="route">行程信息</param>
 /// <returns>route的List</returns>
 public List<Model.DJ_Route> GetLiveRouteByDay(out int MaxLiveDay, int WLiveDay, DJ_TourEnterprise ent, DJ_Route route)
 {
     List<Model.DJ_Route> ListRoute = new List<DJ_Route>();
     MaxLiveDay = 0;
     if (WLiveDay > 0)
     {
         for (int i = route.DayNo; ; i++)
         {
             List<DJ_Route> list = new BLLDJRoute().GetRouteByDayNoandGroupid(i, route.DJ_TourGroup.Id, route.Enterprise.Id).ToList();
             if (list.Count > 0)
             {
                 ListRoute.AddRange(list);
             }
             else
             {
                 MaxLiveDay = i - route.DayNo;
                 break;
             }
         }
     }
     return ListRoute;
 }
 private async Task<IEnumerable<Photo>> GetAllPhotos() {
     var pages = int.Parse(this._view.Pages);
     var photos = new List<Photo>();
     for (var page = 1; page <= pages; page++) {
         photos.AddRange((await GetPhotosResponse(page)).Photos);
     }
     return photos;
 }
Example #22
0
        private static IEnumerable<string> ScanSubDirectories(DirectoryInfo rootDirectory)
        {
            var paths = new List<string>();

            foreach (var directory in rootDirectory.EnumerateDirectories())
            {
                paths.AddRange(FindFiles(directory));
                paths.AddRange(ScanSubDirectories(directory));
            }

            return paths;
        }
Example #23
0
 /// <summary>
 /// 根据日期、删除的样本、出库的样本生成SpecimenRt集合
 /// </summary>
 /// <returns>SpecimenRt集合</returns>
 private List<WebService.SpecimenRt> GetSpecimenRtList()
 {
     //创建回发数据对象
     List<WebService.SpecimenRt> SpecimenRtList = new List<WebService.SpecimenRt>();
     //创建查询日期(2015.02.12,2015.03.13)
     string date = string.Format("{0},{1}", fpExtendDatabase.GetSpecimenRtLogLastPostBackDate(GetUserName()).ToString("yyyy.MM.dd"), DateTime.Now.AddDays(-1).ToString("yyyy.MM.dd"));
     if (CreateSpecimenRtWithSamples_By_Date(date).Count > 0)
     {
         SpecimenRtList.AddRange(CreateSpecimenRtWithSamples_By_Date(date));
     }
     if (CreateSpecimenRtWithSamples_Out().Count > 0)
     {
         SpecimenRtList.AddRange(CreateSpecimenRtWithSamples_Out());
     }
     if (CreateSpecimenRtWithSamples_Trashbin().Count > 0)
     {
         SpecimenRtList.AddRange(CreateSpecimenRtWithSamples_Trashbin());
     }
     return SpecimenRtList;
 }
Example #24
0
        /// <summary>
        /// Pushes the version taken as a parameter
        /// Will return any changes that conflicts
        /// IMPORTANT: The version is not commited at the server before null is returned!
        /// </summary>
        /// <param name="path">The path to the repository to push</param>
        /// <param name="number">The version number used to identify the right version</param>
        /// <param name="log">The changes given by a number of text-.</param>
        /// <param name="user">The user to submit changes.</param>
        /// <returns>
        /// Any changes that conflicts or null if version is commited
        /// </returns>
        /// <exception cref="System.ArgumentNullException">Log can't be null</exception>
        /// <exception cref="System.ArgumentException">Log can't be empty</exception>
        public string[][] PushVersion(String path, int number, string[] log, User user)
        {
            if (log == null) throw new ArgumentNullException("Log can't be null");
            if (log.Length < 1) throw new ArgumentException("Log can't be empty");
            if (user == null) throw new ArgumentNullException("User can't be null");
            if (String.IsNullOrEmpty(user.Name)) throw new ArgumentException("User's name is invalid: " + user.Name);
            if (String.IsNullOrEmpty(user.Password)) throw new ArgumentException("User's password is invalid");
            if (user.MAC == null) throw new ArgumentNullException("User's MAC address is invalid (" + user.MAC + " and can therefore not push");

            Console.WriteLine("[" + DateTime.Now + "]: " + "User is pushing to the server: " + user.MAC);

            //See if the user is known - if not: Throw an exception
            //Connect(user);

            var returnArray = new string[0][];

            // Test that the version number is correct - otherwise we'll just store things at the wrong places.
            var vcs = new ServerVersionControlSystem(path, _fileSystem);
            var currentVersion = vcs.GetLatestVersionNumber();
            if (currentVersion != number - 1)
            {
                throw new ArgumentException("Can not push version " + number + " to the server version " + currentVersion);
            }

            // If the last user that attempted to push is the same as the current user, no conflicts will occur.
            if (PushedLastVersion(user))
            {
                // We can assume that everything has been resolved client side and execute all the changes made
                IList<AbstractChange> changeList = ChangeParser.ParseChanges(log).Where(item => item != null).ToList();

                // Store the version
                SaveChanges(number, user, vcs, changeList);
            }
            else
            {
                String[] simpleChanges = SearchForSimpleChanges(log);
                String[,] complexChanges = SearchForComplexChanges(log);
                ISet<String> conflictingPathsOnServerSet = new SortedSet<string>();
                ISet<String> conflictingPathsOnClientSet = new SortedSet<string>();

                //Get paths to all text files in project directory and all sub directories.
                String absolutePath = vcs.GetFileSystemRoot() + path;
                IList<String> projectFilesList = new List<string>(Directory.GetFileSystemEntries(absolutePath, "*", SearchOption.AllDirectories).Where(s => s.Contains(FileSystem.META_DIR) == false));

                // Discover potential conflicts
                for (int i = 0; i < projectFilesList.Count; i++)
                {
                    projectFilesList[i] = projectFilesList[i].Substring(vcs.GetFileSystemRoot().Length);
                }

                foreach (String filePath in simpleChanges)
                {
                    if (projectFilesList.Contains(filePath))
                    {
                        conflictingPathsOnServerSet.Add(filePath);
                        conflictingPathsOnClientSet.Add(filePath);
                    }
                }
                for (int i = 0; i < complexChanges.Length; i++)
                {
                    if (projectFilesList.Contains(complexChanges[i, 0]))
                    {
                        conflictingPathsOnServerSet.Add(complexChanges[i, 0]);
                        conflictingPathsOnClientSet.Add(complexChanges[i, 1]);
                    }
                }

                // If no conflicts arises we can save the change to the file system
                if (conflictingPathsOnServerSet.Count == 0)
                {
                    SaveChanges(number, user, vcs, ChangeParser.ParseChanges(log));
                }
                else // Otherwise we find the conflicting paths and return the contents of the file on the
                // server for the client to merge
                {
                    IList<String> conflictingPathsOnServer = new List<string>(conflictingPathsOnServerSet);
                    IList<String> conflictingPathsOnClient = new List<string>(conflictingPathsOnClientSet);
                    var list = new List<string[]>();
                    for (int i = 0; i < conflictingPathsOnServer.Count; i++)
                    {
                        var fileList = new List<string>() { conflictingPathsOnClient[i] };
                        fileList.AddRange(vcs.ReadAllLines(conflictingPathsOnServer[i]));
                        list.Add(fileList.ToArray());
                    }
                    returnArray = list.ToArray();
                }
            }

            // Save the last MAC adress
            _lastPushUser = user.Name;
            //AddToPushHistory(user);

            // Return the conflicts to the client
            return returnArray;
        }
Example #25
0
        static void Main(string[] args)
        {
            //Business.SMS.Instance.SendSMS("Mensagem de teste!!", "+5511965579593");
            Console.WriteLine("Olá!! Vamos começar =)");

            Console.WriteLine("Começando pelo começo, importar o CSV? S/N");

            var csv = Console.ReadLine();

            #region importar dados
            if (csv != null && csv.ToLower() == "s")
            {
                var list = new List<Models.Lentidao>();
                var reader = new StreamReader(File.OpenRead(@"Content\Lentidao.csv"), Encoding.Default);
                reader.ReadLine();
                while (!reader.EndOfStream)
                {
                    var line = reader.ReadLine();
                    if (!String.IsNullOrWhiteSpace(line))
                    {
                        string[] values = line.Split(';');
                        if (values.Length >= 12)
                        {
                            list.Add(new Models.Lentidao
                            {
                                DataHora = Convert.ToDateTime(values[1]),
                                IdCorredor = Convert.ToInt32(values[2]),
                                Corredor = values[3],
                                Sentido = values[4],
                                Pista = values[5],
                                ExtensaoPista = Convert.ToInt32(values[6]),
                                InicioLentidao = values[7],
                                TerminoLentidao = values[8],
                                ReferenciaNumericaInicioLentidao = Convert.ToInt32(values[9]),
                                ExensaoLentidao = Convert.ToInt32(values[10]),
                                Regiao = values[11]
                            });
                        }
                    }
                }

                using (var context = new DatabaseContext())
                {
                    context.BulkInsert(list);
                }
                Console.ForegroundColor = ConsoleColor.Blue;
                Console.WriteLine("Uffa!! Terminamos, vamos pro próximo =)");
                Console.ResetColor();
            }
            #endregion

            Console.WriteLine("Vamos fazer a query... (sem view, vai demorar)");

            using (var context = new DatabaseContext())
            {
                context.Database.Log = Console.WriteLine;
                Console.WriteLine("Inserir Lentidão Consolidada? S/N");
                var s = Console.ReadLine();

                var todos = new List<Models.LentidaoConsolidado>();
                if (s != null && s.ToLower() == "s")
                {

                    todos = context.Lentidoes
                        .GroupBy(a => new {
                            a.InicioLentidao,
                            a.TerminoLentidao,
                            a.ReferenciaNumericaInicioLentidao,
                            a.Regiao})
                        .Select(a=> new
                        {
                            Total = a.Count(),
                            TerminoLentidao = a.Key.TerminoLentidao,
                            InicioLentidao = a.Key.InicioLentidao,
                            ReferenciaNumericaInicioLentidao = a.Key.ReferenciaNumericaInicioLentidao,
                            Regiao = a.Key.Regiao
                        })
                        .OrderByDescending(a => a.Total).Skip(1).ToList().Select(a => new Models.LentidaoConsolidado
                        {
                            Total = a.Total,
                            TerminoLentidao = a.TerminoLentidao,
                            InicioLentidao = a.InicioLentidao,
                            ReferenciaNumericaInicioLentidao = a.ReferenciaNumericaInicioLentidao,
                            Regiao = a.Regiao
                        }).ToList();

                    context.BulkInsert(todos);
                }

                todos = context.LentidaoConsolidados.Where(a=>!a.Steps.Any()).ToList();

                var stps = new List<Models.Step>();

                var count = 0;
                foreach(var todo in todos)
                {

                    count++;
                    var directionsRequest = new DirectionsRequest()
                    {
                        Origin = String.Format("{0} {1}, São Paulo - SP, Brasil", TratarEndereco(todo.InicioLentidao), todo.ReferenciaNumericaInicioLentidao),
                        Destination = String.Format("{0}, São Paulo - SP, Brasil", todo.TerminoLentidao),
                        SigningKey = "AIzaSyAl8V3SnsqpCWA1SmyMH0g-PaOkfN5J5LA",
                    };

                    var directions = GoogleMaps.Directions.Query(directionsRequest);

                    if (directions.Status == DirectionsStatusCodes.OK)
                    {
                        var legs = directions.Routes.First().Legs;

                        foreach (var leg in legs)
                        {
                            if (leg.Distance.Value > 20000)
                            {
                                Console.ForegroundColor = ConsoleColor.Red;
                                Console.WriteLine(
                                    String.Format("Xiiii, mais do que 20 quilômetros? Tá suspeito esse registro..."),
                                    new object {});
                                Console.WriteLine(todo);
                                Console.ResetColor();
                            }
                            else
                            {
                                var steps = leg.Steps;

                                stps.AddRange(steps.Select(step => new Models.Step
                                {
                                    PosicaoGeografica = DbGeography.FromText(Business.Ocorrencia.Instance.GetGeographyTextFromLatlng(step.StartLocation.Latitude, step.StartLocation.Longitude)),
                                    FkLentidaoConsolidado = todo.Id
                                }));

                                count = count + stps.Count;
                            }
                        }
                    }

                    if (count > 500)
                    {
                        if (count > 500)
                        {
                            using (var context2 = new DatabaseContext())
                            {
                                try
                                {
                                    context2.Steps.AddRange(stps.Where(a => a.PosicaoGeografica != null));
                                }
                                catch (Exception)
                                {
                                }
                                context2.SaveChanges();
                                stps = new List<Models.Step>();
                                count = 0;
                            }
                        }

                    }

                    Console.WriteLine(directions);
                };

                context.SaveChanges();

            }
        }
Example #26
0
        private void BuildRealPath()
        {
            int horLength = map.GetLength(0);
            int vertLength = map.GetLength(1);
            Point currentPosition = Point.Empty;
            Point destination = Point.Empty;
            for (int i = 0; i < horLength; i++)
            {
                for (int j = 0; j < vertLength; j++)
                {
                    if (this.mapWithIdealPath[i, j] == MyRoadType.CurrentPosition)
                    {
                        currentPosition = new Point(i, j);
                    }

                    if (this.mapWithIdealPath[i, j] == MyRoadType.Destination)
                    {
                        destination = new Point(i, j);
                    }
                }
            }

            HashSet<Point> usedPoints = new HashSet<Point>();
            List<Point> currentLevel = new List<Point> { destination };
            List<Point> nextLevel = new List<Point>();
            Action<Point> addIfIdeal = p =>
                {
                    if (p.X >= 0 && p.X < horLength && p.Y >= 0 && p.Y < vertLength
                        && this.mapWithIdealPath[p.X, p.Y] == MyRoadType.IdealPath)
                    {
                        nextLevel.Add(p);
                    }
                };

            while (true)
            {
                foreach (var point in currentLevel)
                {
                    if (!usedPoints.Contains(point))
                    {
                        if (CanDriveFromTo(currentPosition, point))
                        {
                            this.nextPoint = new PointF((point.X + 0.5f) * MyTileSize, (point.Y + 0.5f) * MyTileSize);
                            return;
                        }

                        usedPoints.Add(point);
                        addIfIdeal(new Point(point.X - 1, point.Y - 1));
                        addIfIdeal(new Point(point.X, point.Y - 1));
                        addIfIdeal(new Point(point.X + 1, point.Y - 1));
                        addIfIdeal(new Point(point.X - 1, point.Y));
                        addIfIdeal(new Point(point.X + 1, point.Y));
                        addIfIdeal(new Point(point.X - 1, point.Y + 1));
                        addIfIdeal(new Point(point.X, point.Y + 1));
                        addIfIdeal(new Point(point.X + 1, point.Y + 1));
                    }
                }

                if (nextLevel.Count == 0)
                {
                    break;
                }

                currentLevel.Clear();
                currentLevel.AddRange(nextLevel);
                nextLevel.Clear();
            }

            // TODO: We should not be here but we are. Fix this!!!
            this.nextPoint = new PointF((destination.X + 0.5f) * MyTileSize, (destination.Y + 0.5f) * MyTileSize);
        }
Example #27
0
        private void UpdateAlbumArt(object sender, DoWorkEventArgs args)
        {
            var toUpdate = new List<Album>();
            using (var repo = DataAccessContext.GetRepository())
            {
                var albums = repo.Albums.Select(x => x);
                toUpdate.AddRange(albums.Where(a => repo.Images.Count(x => x.LinkedId == a.Id) == 0));
            }

            Parallel.ForEach(toUpdate, new ParallelOptions {MaxDegreeOfParallelism = 4},
                             (album) =>
                             	{
                                    using (var repo = DataAccessContext.GetRepository())
                                    {
                                        var artistName = repo.Artists.Where(x => x.Id == album.ArtistId).First().Name;
                                        var image =
                                            API.Album.GetInfo(album.Id, artistName, album.Name).Images[ImageSize.ExtraLarge];
                                        if (image.Length == 0)
                                            return;
                                        var client = new WebClient();
                                        var bytes = client.DownloadData(image);
                                        Binary imgData;
                                        BitmapImage bitmap;
                                        int height;
                                        int width;
                                        try
                                        {
                                            bitmap = ImageUtilities.ImageFromBuffer(bytes);
                                            height = (int) bitmap.Height;
                                            width = (int) bitmap.Width;
                                            imgData = new Binary(bytes);
                                        }
                                        catch (Exception e)
                                        {
                                            try
                                            {
                                                bitmap = ImageUtilities.ImageFromGDIPlus(bytes);
                                                height = (int) bitmap.Height;
                                                width = (int) bitmap.Width;

                                                var b = ImageUtilities.BufferFromImage(bitmap);

                                                //var fs = File.OpenRead(@"C:\Temp\" + guid + ".bmp");
                                                //var b = new byte[fs.Length];
                                                //fs.Read(b, 0, (int) fs.Length);
                                                //fs.Close();

                                                imgData = new Binary(b);
                                            }
                                            catch (Exception e1)
                                            {
                                                return;
                                            }
                                        }

                                        var img = new Image
                                                  	{
                                                  		Id = Guid.NewGuid(),
                                                  		Size = (int) ImageSize.ExtraLarge,
                                                  		Height = height,
                                                  		Width = width,
                                                  		ImageData = imgData,
                                                  		Url = image,
                                                  		LinkedId = album.Id
                                                  	};

                                        repo.Images.InsertOnSubmit(img);
                                        repo.SubmitChanges();
                                    }

                             		ReportProgress(100, album);
                             	}
                );
        }
Example #28
0
        /// <summary>
        /// Lists the activities that matches selected criteria (type/period).
        /// </summary>
        private async void ListActivities()
        {
            DateTime? ldtStart = null;
            DateTime? ldtEnd = null;
            MSHealthActivityType loActivityType = MSHealthActivityType.Unknown;
            MSHealthSplitDistanceType loDistance = MSHealthSplitDistanceType.None;

            try
            {
                IsRunningRequest = true;
                Activities = null;
                // Check if at least one Activity Type was selected
                bool lbFilterActivityType = FilterActivityExercise | FilterActivityRun | FilterActivityBike |
                                            FilterActivityGolf | FilterActivitySleep | FilterActivityGuided |
                                            FilterActivityHike;
                if (!lbFilterActivityType)
                {
#if WINDOWS_UWP
                    await moDialogService.ShowMessage(Resources.Strings.MessageContentSelectActivityType,
                                                      Resources.Strings.MessageTitleFilterActivities);
#endif
                    return;
                }
                // Determine Activity Types to filter
                if (FilterActivityExercise)
                    loActivityType |= MSHealthActivityType.FreePlay;
                if (FilterActivityRun)
                    loActivityType |= MSHealthActivityType.Run;
                if (FilterActivityBike)
                    loActivityType |= MSHealthActivityType.Bike;
                if (FilterActivityGolf)
                    loActivityType |= MSHealthActivityType.Golf;
                if (FilterActivitySleep)
                    loActivityType |= MSHealthActivityType.Sleep;
                if (FilterActivityGuided)
                    loActivityType |= MSHealthActivityType.GuidedWorkout;
                if (FilterActivityHike)
                    loActivityType |= MSHealthActivityType.Hike;
                // Determine Period to filter
                switch (Settings.MSHealthFilterPeriod)
                {
                    case Settings.PERIOD_DAY:
                        ldtEnd = DateTime.Today.AddDays(1).AddMilliseconds(-1);
                        ldtStart = DateTime.Today.AddDays(-1);
                        break;
                    case Settings.PERIOD_WEEK:
                        ldtEnd = DateTime.Today.AddDays(1).AddMilliseconds(-1);
                        ldtStart = DateTime.Today.AddDays(-7);
                        break;
                    case Settings.PERIOD_MONTH:
                        ldtEnd = DateTime.Today.AddDays(1).AddMilliseconds(-1);
                        ldtStart = DateTime.Today.AddMonths(-1);
                        break;
                    case Settings.PERIOD_YEAR:
                        ldtEnd = DateTime.Today.AddDays(1).AddMilliseconds(-1);
                        ldtStart = DateTime.Today.AddYears(-1);
                        break;
                }
                // Determine Distance Unit to retrieve
                switch (Settings.MSHealthFilterDistance)
                {
                    case DistanceUnit.DISTANCE_MILE:
                        loDistance = MSHealthSplitDistanceType.Mile;
                        break;
                    case DistanceUnit.DISTANCE_KILOMETER:
                        loDistance = MSHealthSplitDistanceType.Kilometer;
                        break;
                }
                // Find activities with selected criteria, and update MSHealth Token
                MSHealthActivities loActivities = await moMSHealthClient.ListActivities(startTime: ldtStart,
                                                                                        endTime: ldtEnd,
                                                                                        type: loActivityType,
                                                                                        splitDistanceType: loDistance);
                Settings.MSHealthToken = moMSHealthClient.Token;
                // Parse each separated activity list into one single activity list
                List<MSHealthActivity> loActivitiesList = new List<MSHealthActivity>();
                if (loActivities.BikeActivities != null &&
                    loActivities.BikeActivities.Any())
                    loActivitiesList.AddRange(loActivities.BikeActivities);
                if (loActivities.RunActivities != null &&
                    loActivities.RunActivities.Any())
                    loActivitiesList.AddRange(loActivities.RunActivities);
                if (loActivities.SleepActivities != null &&
                    loActivities.SleepActivities.Any())
                    loActivitiesList.AddRange(loActivities.SleepActivities);
                if (loActivities.FreePlayActivities != null &&
                    loActivities.FreePlayActivities.Any())
                    loActivitiesList.AddRange(loActivities.FreePlayActivities);
                if (loActivities.GolfActivities != null &&
                    loActivities.GolfActivities.Any())
                    loActivitiesList.AddRange(loActivities.GolfActivities);
                if (loActivities.GuidedWorkoutActivities != null &&
                    loActivities.GuidedWorkoutActivities.Any())
                    loActivitiesList.AddRange(loActivities.GuidedWorkoutActivities);
                if (loActivities.HikeActivities != null &&
                    loActivities.HikeActivities.Any())
                    loActivitiesList.AddRange(loActivities.HikeActivities);
                // Sort descending by Start Time and append to Bindable property
                loActivitiesList = loActivitiesList.OrderByDescending(loAct => loAct.StartTime).ToList();
                Activities = new ObservableCollection<MSHealthActivity>(loActivitiesList);
            }
            catch (Exception loException)
            {
                // Handle exceptions (just for debugging purposes). TODO: Delete this code
                if (System.Diagnostics.Debugger.IsAttached)
                {
                    System.Diagnostics.Debug.WriteLine(loException.StackTrace);
                    System.Diagnostics.Debugger.Break();
                } // Handle exceptions (just for debugging purposes)
                  // Show error message
#if WINDOWS_UWP
                await moDialogService.ShowError(Resources.Strings.MessageContentErrorOperation,
                                                Resources.Strings.MessageTitleError,
                                                Resources.Strings.MessageButtonOK,
                                                null);
#endif
            }
            finally
            {
                IsRunningRequest = false;
            }
        }
Example #29
0
        private void UpdateArtistImages(object sender, DoWorkEventArgs args)
        {
            var toUpdate = new List<Artist>();
            using (var repo = DataAccessContext.GetRepository())
            {
                var artists = repo.Artists.Select(x => x);

                toUpdate.AddRange(artists.Where(a => repo.Images.Count(x => x.LinkedId == a.Id) == 0));
            }

            Parallel.ForEach(toUpdate, new ParallelOptions {MaxDegreeOfParallelism = 4},
                             delegate(Artist a)
                             	{
                             		var image = API.Artist.GetImages(a.Name, 10);
                             		foreach (var i in image.ImageUrls)
                             		{
                             			var client = new WebClient();
                             			var bytes = client.DownloadData(i.Value);
                             			Binary imgData;
                             			BitmapImage bitmap;
                             			int height;
                             			int width;
                             			try
                             			{
                             				bitmap = ImageUtilities.ImageFromBuffer(bytes);
                             				height = (int) bitmap.Height;
                             				width = (int) bitmap.Width;
                             				imgData = new Binary(bytes);
                             			}
                             			catch (Exception e)
                             			{
                             				try
                             				{
                             					bitmap = ImageUtilities.ImageFromGDIPlus(bytes);
                             					height = (int) bitmap.Height;
                             					width = (int) bitmap.Width;

                             					var b = ImageUtilities.BufferFromImage(bitmap);

                             					//var fs = File.OpenRead(@"C:\Temp\" + guid + ".bmp");
                             					//var b = new byte[fs.Length];
                             					//fs.Read(b, 0, (int) fs.Length);
                             					//fs.Close();

                             					imgData = new Binary(b);
                             				}
                             				catch (Exception e1)
                             				{
                             					return;
                             				}
                             			}
                             			using (var repo = DataAccessContext.GetRepository())
                             			{

                             				var img = new Image
                             				          	{
                             				          		Id = Guid.NewGuid(),
                             				          		Size = (int) i.Key,
                             				          		Height = height,
                             				          		Width = width,
                             				          		ImageData = imgData,
                             				          		Url = i.Value,
                             				          		LinkedId = a.Id
                             				          	};

                             				repo.Images.InsertOnSubmit(img);
                             				repo.SubmitChanges();
                             			}
                             		}

                             		ReportProgress(100, a);
                             	});
        }