コード例 #1
0
        public IMessage Parse(string sMessage)
        {
            IMessage        message;
            FieldCollection fields   = new FieldCollection();
            string          sMsgType = null;
            IField          field;

            FieldReaderFIX reader = new FieldReaderFIX(sMessage);

            while ((field = reader.GetNextField()) != null)
            {
                fields.Add(field);

                if (field.Tag == Message.TAG_MsgType && field.Value != null && field.Value.Length > 0)
                {
                    sMsgType = field.Value;
                }
            }

            if (sMsgType == null || sMsgType.Length == 0)
            {
                if (log.IsWarnEnabled)
                {
                    log.WarnFormat("Parse - Failed to parse MsgType from message / Message={0}", sMessage);
                }
                throw new Exception("Unable to parse MsgType");
            }
            message = CreateInstance(sMsgType);
            if (message == null)
            {
                if (log.IsWarnEnabled)
                {
                    log.WarnFormat("Parse - Failed to create instance of the message / MsgType={0}", sMsgType);
                }
                throw new Exception("Failed to create instance of the message");
            }

            MessageHelper helper = CreateMessageHelper(message);

            if (helper == null)
            {
                if (log.IsWarnEnabled)
                {
                    log.WarnFormat("Parse - Failed to create instance of MessageHelper / MsgType={0}", sMsgType);
                }
                throw new Exception("Failed to create instance of MessageHelper");
            }

            message.MessageRaw = sMessage;

            //Parse individual fields
            field = null;
            try
            {
                for (int i = 0; i < fields.Count; i++)
                {
                    field = fields[i];
                    helper.ParseField(field);
                }
            }
            catch (Exception ex)
            {
                log.Warn(string.Format("Parse - Error parsing {0}", field), ex);
                if (field == null)
                {
                    throw new Exception(string.Format("Error parsing {0}", field), ex);
                }
                else
                {
                    Exception exParse = CreateInstanceParseFieldException(
                        string.Format("Error parsing {0}", field), ex, field, sMessage);
                    throw exParse;
                }
            }

            return(message);
        }
コード例 #2
0
 public CustomPoint AddField(string key, int value)
 {
     _fields.Add(key, value);
     return(this);
 }
コード例 #3
0
        public virtual FieldCollection GetFields(string tableName)
        {
            using (var connection = CreateDbConnection(DbProviderName, ConnectionDetails.ConnectionString))
                using (var command = connection.CreateCommand())
                {
                    command.CommandType = CommandType.Text;
                    command.CommandText = string.Format(Constants.Data.CMD_SELECT_INFO_SCHEMA_COLUMNS, tableName);
                    var fields = new FieldCollection();

                    connection.Open();
                    using (var reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            var field = new Field();
                            field.Name = reader.GetString(0);
                            if (!reader.IsDBNull(1))
                            {
                                field.Ordinal = reader.GetInt32(1);
                            }
                            if (!reader.IsDBNull(2))
                            {
                                field.Type = GetDataMigratorFieldType(reader.GetString(2));
                            }
                            if (!reader.IsDBNull(3))
                            {
                                field.IsRequired = reader.GetString(3) == "NO";
                            }
                            if (!reader.IsDBNull(4))
                            {
                                field.MaxLength = reader.GetInt32(4);
                            }
                            fields.Add(field);
                        }
                    }
                    connection.Close();

                    try
                    {
                        command.CommandText = string.Format(Constants.Data.CMD_IS_PRIMARY_KEY_FORMAT, tableName);

                        connection.Open();
                        using (var reader = command.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                string pkColumn = reader.GetString(0);
                                var    match    = fields.SingleOrDefault(f => f.Name == pkColumn);
                                if (match != null)
                                {
                                    match.IsPrimaryKey = true;
                                }
                            }
                        }

                        connection.Close();
                    }
                    catch (Exception x)
                    {
                        TraceService.Instance.WriteConcat(TraceEvent.Error, "Error: Could not get primary key info - ", x.Message);
                        if (connection.State != ConnectionState.Closed)
                        {
                            connection.Close();
                        }
                    }

                    return(fields);
                }
        }
コード例 #4
0
        public void Apply(Section section)
        {
            // section color
            section.BackColor = BackColor;

            // field font/color
            double          left   = double.MaxValue;
            double          right  = double.MinValue;
            FieldCollection fields = section.Fields;

            foreach (FieldBase f in fields)
            {
                var t      = f.GetType();
                var pdFont = t.GetProperty("Font");
                if (pdFont != null)
                {
                    var fontHolder = pdFont.GetValue(f, null) as FontHolder;
                    if (fontHolder != null)
                    {
                        fontHolder.Font = this.Font;
                    }
                }
                var pdForeColor = t.GetProperty("ForeColor");
                if (pdForeColor != null)
                {
                    pdForeColor.SetValue(f, this.ForeColor, null);
                }
                left  = Math.Min(left, f.Left);
                right = Math.Max(right, f.Left + f.Width);
            }
            if (fields.Count == 0)
            {
                left  = 0;
                right = section.ParentReport.Layout.Width;
            }

            // delete old lines
            for (int i = 0; i < fields.Count; i++)
            {
                if (fields[i].Name.StartsWith(STYLE_LINE_FIELD_NAME))
                {
                    fields.RemoveAt(i);
                    i--;
                }
            }

            // disable warnings about using Border instead of BorderColor etc:
#pragma warning disable CS0618
            // add lines
            if (section.Height > LINE_WIDTH && LineColor != Color.Transparent && (LineAbove || LineBelow))
            {
                if (LineAbove)
                {
                    string name = GetUniqueFieldName(fields, STYLE_LINE_FIELD_NAME);
                    Field  f    = fields.Add(name, string.Empty, left, 0, right - left, LINE_WIDTH);

                    f.BorderColor = LineColor;
                    f.BorderStyle = BorderStyleEnum.Solid;
                    f.Shape       = new Doc.LineShape(Doc.LineSlantEnum.NoSlant);
                    //f.BackColor = LineColor; // not as good as lines
                }
                if (LineBelow)
                {
                    string name = GetUniqueFieldName(fields, STYLE_LINE_FIELD_NAME);
                    Field  f    = fields.Add(name, string.Empty, left, section.Height - LINE_WIDTH, right - left, LINE_WIDTH);

                    f.BorderColor = LineColor;
                    f.BorderStyle = BorderStyleEnum.Solid;
                    f.Shape       = new Doc.LineShape(Doc.LineSlantEnum.NoSlant);
                    //f.BackColor = LineColor; // not as good as lines
                    f.Anchor = AnchorEnum.Bottom;
                }
            }
#pragma warning restore CS0618

            // create script to apply alternate back color
            C1FlexReport rpt = section.ParentReport;
            if (section == rpt.Sections.Detail)
            {
                rpt.OnOpen      = RemoveStyleScript(rpt.OnOpen);
                section.OnPrint = RemoveStyleScript(section.OnPrint);
                if (!AlternateColor.Equals(Color.Transparent) && !AlternateColor.Equals(BackColor))
                {
                    rpt.OnOpen      = rpt.OnOpen + SCRIPT_ONOPEN;
                    section.OnPrint = section.OnPrint + string.Format(SCRIPT_ONPRINT,
                                                                      BackColor.R, BackColor.G, BackColor.B,
                                                                      AlternateColor.R, AlternateColor.G, AlternateColor.B);
                }
            }
        }
コード例 #5
0
        public void Apply(Section section)
        {
            // section color
            section.BackColor = BackColor;

            // field font/color
            double          left   = double.MaxValue;
            double          right  = double.MinValue;
            FieldCollection fields = section.Fields;

            foreach (Field f in fields)
            {
                f.Font      = this.Font;
                f.ForeColor = this.ForeColor;
                left        = Math.Min(left, f.Left);
                right       = Math.Max(right, f.Left + f.Width);
            }
            if (fields.Count == 0)
            {
                left  = 0;
                right = section.ParentReport.Layout.Width;
            }

            // delete old lines
            for (int i = 0; i < fields.Count; i++)
            {
                if (fields[i].Name.StartsWith(STYLE_LINE_FIELD_NAME))
                {
                    fields.RemoveAt(i);
                    i--;
                }
            }

            // add lines
            if (section.Height > LINE_WIDTH && LineColor != Color.Transparent && (LineAbove || LineBelow))
            {
                if (LineAbove)
                {
                    string name = GetUniqueFieldName(fields, STYLE_LINE_FIELD_NAME);
                    Field  f    = fields.Add(name, string.Empty, left, 0, right - left, LINE_WIDTH);

                    f.BorderColor = LineColor;
                    f.BorderStyle = BorderStyleEnum.Solid;
                    f.LineSlant   = LineSlantEnum.NoSlant;
                    //f.BackColor = LineColor; // not as good as lines
                }
                if (LineBelow)
                {
                    string name = GetUniqueFieldName(fields, STYLE_LINE_FIELD_NAME);
                    Field  f    = fields.Add(name, string.Empty, left, section.Height - LINE_WIDTH, right - left, LINE_WIDTH);

                    f.BorderColor = LineColor;
                    f.BorderStyle = BorderStyleEnum.Solid;
                    f.LineSlant   = LineSlantEnum.NoSlant;
                    //f.BackColor = LineColor; // not as good as lines

                    f.Anchor = AnchorEnum.Bottom;
                }
            }

            // create script to apply alternate back color
            C1Report rpt = section.ParentReport;

            if (section == rpt.Sections.Detail)
            {
                rpt.OnOpen      = RemoveStyleScript(rpt.OnOpen);
                section.OnPrint = RemoveStyleScript(section.OnPrint);
                if (!AlternateColor.Equals(Color.Transparent) && !AlternateColor.Equals(BackColor))
                {
                    rpt.OnOpen      = rpt.OnOpen + SCRIPT_ONOPEN;
                    section.OnPrint = section.OnPrint + string.Format(SCRIPT_ONPRINT,
                                                                      BackColor.R, BackColor.G, BackColor.B,
                                                                      AlternateColor.R, AlternateColor.G, AlternateColor.B);
                }
            }
        }
コード例 #6
0
        public Sobiens.Connectors.Entities.FieldCollection GetFields(ISiteSetting siteSetting, string dbName, string tableName)
        {
            try
            {
                Sobiens.Connectors.Entities.FieldCollection fields = new FieldCollection();
                using (SqlConnection con = new SqlConnection(this.GetConnectionString(siteSetting, dbName)))
                {
                    con.Open();

                    // Set up a command with the given query and associate
                    // this with the current connection.
                    using (SqlCommand cmd = new SqlCommand("SELECT A.name columnname, B.name columntype, A.is_nullable is_nullable, A.is_identity is_identity, A.max_length max_length FROM sys.columns A" +
                                                           " INNER JOIN sys.types B ON A.system_type_id = B.system_type_id" +
                                                           " WHERE object_id = OBJECT_ID('" + tableName + "') and B.name <> 'sysname'", con))
                    {
                        using (IDataReader dr = cmd.ExecuteReader())
                        {
                            while (dr.Read())
                            {
                                string     fieldName = dr["columnname"].ToString();
                                bool       required  = !(bool)dr["is_nullable"];
                                int        maxLength = int.Parse(dr["max_length"].ToString());
                                FieldTypes fieldType = FieldTypes.Text;
                                switch (dr["columntype"].ToString().ToLower())
                                {
                                case "int":
                                case "bigint":
                                case "float":
                                case "decimal":
                                case "numeric":
                                case "smallint":
                                case "tinyint":
                                    fieldType = FieldTypes.Number;
                                    break;

                                case "bit":
                                    fieldType = FieldTypes.Boolean;
                                    break;

                                case "date":
                                case "datetime":
                                case "datetime2":
                                case "smalldatetime":
                                    fieldType = FieldTypes.DateTime;
                                    break;
                                }

                                Field field = new Field();
                                field.Name         = fieldName;
                                field.DisplayName  = fieldName;
                                field.Required     = required;
                                field.MaxLength    = maxLength;
                                field.Type         = fieldType;
                                field.FromBaseType = false;
                                fields.Add(field);
                            }
                        }
                    }
                }

                return(fields);
            }
            catch (Exception ex)
            {
                string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
                //LogManager.LogAndShowException(methodName, ex);
                throw ex;
            }
        }
        private void Populate()
        {
            if (QueryResult.SiteSetting == null)
            {
                return;
            }

            if (SourceFolder == null)
            {
                SiteSetting siteSetting = (SiteSetting)QueryResult.SiteSetting;
                SourceFolder = ApplicationContext.Current.GetFolder((SiteSetting)QueryResult.SiteSetting, new BasicFolderDefinition()
                {
                    FolderUrl     = siteSetting.Url + "/" + QueryResult.FolderPath,
                    SiteSettingID = QueryResult.SiteSetting.ID
                });
            }
            else
            {
                QueryResult.Filters         = new CamlFilters();
                QueryResult.ReferenceFields = new List <QueryResultReferenceField>();
            }

            SourceSelectButton.Content = SourceFolder.GetPath();
            QueryResult.ListName       = SourceFolder.GetListName();
            QueryResult.Name           = SourceFolder.GetListName();
            SourceSiteSetting          = ApplicationContext.Current.GetSiteSetting(SourceFolder.SiteSettingID);
            SourceFields = ApplicationContext.Current.GetFields(SourceSiteSetting, SourceFolder);
            string[] requiredFields = new string[] { QueryResult.PrimaryIdFieldName, QueryResult.PrimaryNameFieldName, QueryResult.PrimaryFileReferenceFieldName, QueryResult.ModifiedByFieldName, QueryResult.ModifiedOnFieldName };
            requiredFields = requiredFields.Where(x => !string.IsNullOrEmpty(x)).ToArray();
            foreach (string requiredField in requiredFields)
            {
                Field sourceField = SourceFields.Where(t => t.Name.Equals(requiredField, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
                if (sourceField == null)
                {
                    SourceFields.Add(new Field()
                    {
                        Name        = requiredField,
                        Type        = FieldTypes.Text,
                        DisplayName = requiredField
                    });
                }
            }


            QueryResult.SiteSetting = (SiteSetting)SourceSiteSetting;

            /*
             * List<string> tempSourceFields = new List<string>();
             * tempSourceFields.AddRange(QueryResult.Fields);
             * foreach(string requiredField in RequiredFields)
             * {
             *  if(tempSourceFields.Contains(requiredField) == false)
             *  {
             *      tempSourceFields.Add(requiredField);
             *  }
             * }
             * QueryResult.Fields = tempSourceFields.ToArray();
             */
            QueryResult.IsDocumentLibrary = SourceFolder.IsDocumentLibrary;
            PopulateFilters();

            ViewFieldsMenuItem.Items.Clear();
            foreach (Field field in SourceFields)
            {
                MenuItem mi = new MenuItem();

                CheckBox checkBox = new CheckBox();
                checkBox.Tag                 = field;
                checkBox.Content             = field.DisplayName;
                checkBox.HorizontalAlignment = HorizontalAlignment.Left;
                checkBox.Margin              = new Thickness(0, 0, 0, 0);
                checkBox.VerticalAlignment   = VerticalAlignment.Top;
                checkBox.Click              += CheckBox_Click;
                if (requiredFields.Contains(field.Name) == true)
                {
                    checkBox.IsChecked = true;
                    checkBox.IsEnabled = false;
                    ViewFieldsCheckBoxChanged(checkBox, field);
                    //CheckBox_Click(checkBox, new RoutedEventArgs() { Source = checkBox });
                }
                else
                {
                    checkBox.IsChecked = (localQueryResultMappingSelectFields.Where(t => t.FieldName.Equals(field.Name) == true).Count() > 0 ? true : false);
                }

                mi.Header = checkBox;

                ViewFieldsMenuItem.Items.Add(mi);
            }


            /*
             * if (SourceFolder.IsDocumentLibrary == true)
             * {
             *  if(QueryResult.Fields.Contains("FileRef") == false)
             *  {
             *      List<string> newArray = QueryResult.Fields.ToList();
             *      newArray.Add("FileRef");
             *
             *      QueryResult.Fields = newArray.ToArray();
             *  }
             * }
             */
        }
コード例 #8
0
        private void button1_Click(object sender, System.EventArgs e)
        {
            // clear report
            _c1r.Clear();
            _c1r.ReportName        = "Images";
            _c1r.Font              = new Font("Tahoma", 9);
            _c1r.Layout.MarginLeft = 600;

            // configure detail section
            Section   section = _c1r.Sections[SectionTypeEnum.Detail];
            Rectangle rc      = new Rectangle(0, 0, 1600, 1200);

            section.Height  = rc.Height;
            section.Visible = true;
            section.CanGrow = true;

            // add fields
            FieldCollection fc = section.Fields;

            // create ID field
            Field f = fc.Add("fldID", "ID", rc);

            f.Align       = FieldAlignEnum.LeftTop;
            f.Calculated  = true;
            f.BorderStyle = BorderStyleEnum.Solid;

            // create file name field
            rc.Offset(rc.Width + 100, 0);
            f             = fc.Add("fldFileName", "FileName", rc);
            f.Align       = FieldAlignEnum.LeftTop;
            f.WordWrap    = true;
            f.Calculated  = true;
            f.BorderStyle = BorderStyleEnum.Solid;

            // create 1st image field (directly from db)
            rc.Offset(rc.Width + 100, 0);
            rc.Width       = 4000;
            rc.Height      = 4000;
            f              = fc.Add("fldImage", "Image", rc);
            f.Picture      = "Image";
            f.PictureAlign = PictureAlignEnum.Zoom;
            f.BorderStyle  = BorderStyleEnum.Solid;

            // create 2nd image field (laoded from file at render time)
            rc.Offset(rc.Width + 100, 0);
            f = fc.Add("fldFileImage", "", rc);
            f.PictureAlign = PictureAlignEnum.Zoom;
            f.BorderStyle  = BorderStyleEnum.Solid;

            // use script to set Picture property at render time:
            // this takes the iamge filename from the 'fldFileName' calculated field.
            section.OnPrint = "fldFileImage.Picture = fldFileName";

            // set data source
            _c1r.DataSource.Recordset = _dt;

            // show it
            C1.Win.C1Preview.C1PrintPreviewDialog dlg = new C1.Win.C1Preview.C1PrintPreviewDialog();
            dlg.Document = _c1r;
            dlg.ShowDialog();
        }
コード例 #9
0
        public ExportTable Export()
        {
            // 取得縣市對照表
            XmlElement schoolLocationList = Config.GetSchoolLocationList().GetContent().BaseElement;

            // 取得匯出規則描述
            XmlElement        descElement      = StudentBulkProcess.GetExportDescription();
            IFieldFormater    fieldFormater    = new BaseFieldFormater();
            IResponseFormater responseFormater = new ResponseFormater();

            FieldCollection       fieldCollection = fieldFormater.Format(descElement);
            ExportFieldCollection exportFields    = responseFormater.Format(descElement);



            fieldCollection = FieldUtil.Match(fieldCollection, _selectFields);
            exportFields    = FieldUtil.Match(exportFields, _selectFields);

            //// 有選狀態時加入
            //if (_selectFields.FindByDisplayText("狀態") != null)
            //{
            //    fieldCollection.Add(_selectFields.FindByDisplayText("狀態"));
            //    ExportField ex = new ExportField();
            //    ex.DisplayText = "狀態";
            //    ex.RequestName = "StudentStatus";
            //    ex.ColumnIndex = exportFields.Length;
            //    ex.DataType = "";
            //    ex.XPath = "";
            //    exportFields.Add(ex);

            //}


            IRequestGenerator reqGenerator = new ExportStudentRequestGenerator();

            _selectFieldsID = new FieldCollection();
            foreach (Field fd in _selectFields)
            {
                _selectFieldsID.Add(fd);
            }

            if (_selectFieldsID.Find("StudentID") == null)
            {
                Field fd1 = new Field();
                fd1.FieldName   = "StudentID";
                fd1.DisplayText = "學生系統編號";
                _selectFieldsID.Add(fd1);
            }
            reqGenerator.SetSelectedFields(_selectFieldsID);

            // 預設找-1, 不然會傳回所有學生
            ICondition condition = new BaseCondition("ID", "-1");

            reqGenerator.AddCondition(condition);
            foreach (string id in _conditions)
            {
                ICondition condition2 = new BaseCondition("ID", id);
                reqGenerator.AddCondition(condition2);
            }

            reqGenerator.AddOrder(new Order("GradeYear"));
            reqGenerator.AddOrder(new Order("Department"));
            reqGenerator.AddOrder(new Order("RefClassID"));
            reqGenerator.AddOrder(new Order("SeatNo"));

            DSRequest  request  = reqGenerator.Generate();
            DSResponse response = QueryStudent.GetExportList(request);

            ExportTable table = new ExportTable();



            foreach (ExportField field in exportFields)
            {
                table.AddColumn(field);
            }

            //// 取得學生狀態
            //Dictionary<string, string> StudStatusDic = new Dictionary<string, string>();
            //foreach (JHSchool.Data.JHStudentRecord stud in JHSchool.Data.JHStudent.SelectByIDs(K12.Presentation.NLDPanels.Student.SelectedSource ))
            //    StudStatusDic.Add(stud.ID, stud.Status.ToString());

            foreach (XmlElement record in response.GetContent().GetElements("Student"))
            {
                ExportRow row = table.AddRow();
                foreach (ExportField column in table.Columns)
                {
                    int        columnIndex = column.ColumnIndex;
                    ExportCell cell        = row.Cells[columnIndex];

                    XmlNode cellNode = record.SelectSingleNode(column.XPath);

                    //if(column.DisplayText !="狀態")
                    //    cellNode = record.SelectSingleNode(column.XPath);
                    // CustodianOtherInfo/CustodianOtherInfo[1]/EducationDegree[1]

                    #region 這段程式是處理匯入/匯出程式不一致問題
                    if (column.XPath.StartsWith("CustodianOtherInfo/Custodian"))
                    {
                        if (cellNode == null)
                        {
                            string x = column.XPath.Replace("CustodianOtherInfo/Custodian", "CustodianOtherInfo/CustodianOtherInfo");
                            cellNode = record.SelectSingleNode(x);
                            if (cellNode == null)
                            {
                                x        = column.XPath.Replace("CustodianOtherInfo/CustodianOtherInfo", "CustodianOtherInfo/Custodian");
                                cellNode = record.SelectSingleNode(x);
                            }
                        }
                    }
                    if (column.XPath.StartsWith("FatherOtherInfo/Father"))
                    {
                        if (cellNode == null)
                        {
                            string x = column.XPath.Replace("FatherOtherInfo/Father", "FatherOtherInfo/FatherOtherInfo");
                            cellNode = record.SelectSingleNode(x);
                            if (cellNode == null)
                            {
                                x        = column.XPath.Replace("FatherOtherInfo/FatherOtherInfo", "FatherOtherInfo/Father");
                                cellNode = record.SelectSingleNode(x);
                            }
                        }
                    }
                    if (column.XPath.StartsWith("MotherOtherInfo/Mother"))
                    {
                        if (cellNode == null)
                        {
                            string x = column.XPath.Replace("MotherOtherInfo/Mother", "MotherOtherInfo/MotherOtherInfo");
                            cellNode = record.SelectSingleNode(x);
                            if (cellNode == null)
                            {
                                x        = column.XPath.Replace("MotherOtherInfo/MotherOtherInfo", "MotherOtherInfo/Mother");
                                cellNode = record.SelectSingleNode(x);
                            }
                        }
                    }
                    #endregion

                    if (cellNode != null)
                    {
                        if (column.FieldName == "GraduateSchoolLocationCode")
                        {
                            cell.Value = GetCounty(schoolLocationList, cellNode.InnerText);
                        }
                        else if (column.FieldName == "DeptName") //處理科別繼承問題。
                        {
                            //這個欄位的資料一定會被回傳,因為設定了 Mandatory 屬性。
                            XmlNode selfDept = record.SelectSingleNode("SelfDeptName");
                            if (string.IsNullOrEmpty(selfDept.InnerText))
                            {
                                cell.Value = cellNode.InnerText;
                            }
                            else
                            {
                                cell.Value = selfDept.InnerText;
                            }
                        }
                        else if (column.FieldName == "Status")
                        {
                            cell.Value = GetStudStatusStr(cellNode.InnerText);
                        }
                        else
                        {
                            cell.Value = cellNode.InnerText;
                        }
                    }

                    //if (column.DisplayText == "狀態")//record.SelectSingleNode("StudentID")!=null )
                    //{
                    //    // 學生狀態
                    //    if (StudStatusDic.ContainsKey(record.SelectSingleNode("StudentID").InnerText))
                    //        cell.Value = StudStatusDic[record.SelectSingleNode("StudentID").InnerText];
                    //}
                }
            }
            return(table);
        }
コード例 #10
0
ファイル: Helper.cs プロジェクト: SyAbou/sharpointonline
        public static List EnsureLocalNavConfigList(Web web)
        {
            List list = null;

            try
            {
                Logger.LogInfoMessage(String.Format("Ensuring Local Nav Config list for {0} ...", web.Url), true);

                list = web.GetListByUrl(Constants.LocalNavListWebRelativeUrl);
                if (list == null)
                {
                    Logger.LogInfoMessage(String.Format("Creating Local Nav Config list ..."), true);
                    list = web.CreateList(Microsoft.SharePoint.Client.ListTemplateType.GenericList, Constants.LocalNavListTitle, false, true, Constants.LocalNavListWebRelativeUrl, false);
                }

                FieldCollection     fields      = list.Fields;
                View                defaultView = list.DefaultView;
                ViewFieldCollection viewFields  = defaultView.ViewFields;
                web.Context.Load(fields);
                web.Context.Load(defaultView);
                web.Context.Load(viewFields);
                web.Context.ExecuteQueryRetry();

                Logger.LogInfoMessage(String.Format("- Ensuring List Field [{0}] ...", Constants.PnPDisplayOrder_DisplayName), false);
                if (list.FieldExistsById(new Guid(Constants.PnPDisplayOrder_GUID)) == false)
                {
                    fields.Add(web.GetFieldById <Field>(new Guid(Constants.PnPDisplayOrder_GUID), true));
                    viewFields.Add(Constants.PnPDisplayOrder_InternalName);
                    defaultView.Update();
                }
                Logger.LogInfoMessage(String.Format("- Ensuring List Field [{0}] ...", Constants.PnPLinkText_DisplayName), false);
                if (list.FieldExistsById(new Guid(Constants.PnPLinkText_GUID)) == false)
                {
                    fields.Add(web.GetFieldById <Field>(new Guid(Constants.PnPLinkText_GUID), true));
                    viewFields.Add(Constants.PnPLinkText_InternalName);
                    defaultView.Update();
                }
                Logger.LogInfoMessage(String.Format("- Ensuring List Field [{0}] ...", Constants.PnPLinkUrl_DisplayName), false);
                if (list.FieldExistsById(new Guid(Constants.PnPLinkUrl_GUID)) == false)
                {
                    fields.Add(web.GetFieldById <Field>(new Guid(Constants.PnPLinkUrl_GUID), true));
                    viewFields.Add(Constants.PnPLinkUrl_InternalName);
                    defaultView.Update();
                }
                string viewQuery = String.Format(Constants.ListViewQueryFormatString, Constants.PnPDisplayOrder_InternalName);
                if (!defaultView.ViewQuery.Equals(viewQuery, StringComparison.InvariantCultureIgnoreCase))
                {
                    defaultView.ViewQuery = viewQuery;
                    defaultView.Update();
                }
                list.Update();
                web.Context.ExecuteQueryRetry();

                //Initialize the list
                ListItemCollection listItems = list.GetItems(CamlQuery.CreateAllItemsQuery());
                web.Context.Load(listItems);
                web.Context.ExecuteQueryRetry();

                // Initialize the list only if it is empty.
                if (listItems.Count == 0)
                {
                    Logger.LogInfoMessage(String.Format("Initializing Local Nav Config list ..."), false);

                    for (int i = 0; i < 5; i++)
                    {
                        Logger.LogInfoMessage(String.Format("- Adding list item..."), false);

                        ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
                        ListItem listItem = list.AddItem(itemCreateInfo);

                        listItem["Title"] = String.Format("Local Link {0}", i + 1);
                        listItem[Constants.PnPDisplayOrder_InternalName] = (i + 1);
                        listItem[Constants.PnPLinkText_InternalName]     = String.Format("{0} Link {1}", web.Title, i + 1);
                        listItem[Constants.PnPLinkUrl_InternalName]      = Constants.LocalNavLinkUrl;
                        listItem.Update();
                        web.Context.ExecuteQueryRetry();
                    }
                }
                Logger.LogSuccessMessage(String.Format("Ensured Local Nav Config list for {0}", web.Url), false);
            }
            catch (Exception ex)
            {
                Logger.LogErrorMessage(String.Format("EnsureLocalNavConfigList() failed for {0}: Error={1}", web.Url, ex.Message), false);
            }

            return(list);
        }
コード例 #11
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="db"></param>
        /// <param name="recs"></param>
        /// <param name="tracks">true, wenn es sich um Track-IDs handelt.</param>
        public FormCopyToClipboard(DataBase db, int[] recs, bool tracks)
        {
            InitializeComponent();

            FormThemeManager.SetTheme(this);

            records    = recs;
            dataBase   = db;
            copyTracks = tracks;

            comboBoxFieldSeperator.Items.Add(new ComboBoxSeperator("TAB", "\t"));
            comboBoxFieldSeperator.Items.Add(new ComboBoxSeperator(";", ";"));
            comboBoxFieldSeperator.Items.Add(new ComboBoxSeperator(",", ","));

            comboBoxRecordSeperator.Items.Add(new ComboBoxSeperator("CR/LF", "\r\n"));

            FieldCollection selectedFields;

            string[] defaultFields;

            if (copyTracks)
            {
                defaultFields    = new string[2];
                defaultFields[0] = ((int)Field.ArtistTrackName).ToString();
                defaultFields[1] = ((int)Field.TrackTitle).ToString();
            }
            else
            {
                defaultFields    = new string[2];
                defaultFields[0] = ((int)Field.ArtistCDName).ToString();
                defaultFields[1] = ((int)Field.Title).ToString();
            }

            using (RegistryKey regKey = Registry.CurrentUser.OpenSubKey(Global.HitbaseRegistryKey))
            {
                regKey.OpenSubKey(Global.HitbaseRegistryKey);
                string[] stringFields;

                if (copyTracks)
                {
                    stringFields = (string[])regKey.GetValue("CopyToClipboardTrackFields", defaultFields);
                }
                else
                {
                    stringFields = (string[])regKey.GetValue("CopyToClipboardCDFields", defaultFields);
                }

                int iCount = 0;
                selectedFields = new FieldCollection();
                foreach (string s in stringFields)
                {
                    selectedFields.Add((Field)Convert.ToInt32(s));
                }

                string fieldSep = (string)regKey.GetValue("CopyToClipboardFieldSeperator");
                if (fieldSep != null)
                {
                    foreach (ComboBoxSeperator sep in comboBoxFieldSeperator.Items)
                    {
                        if (sep.Value == fieldSep)
                        {
                            comboBoxFieldSeperator.SelectedItem = sep;
                            break;
                        }
                    }
                }
                else
                {
                    comboBoxFieldSeperator.SelectedIndex = 0;
                }

                string recordSep = (string)regKey.GetValue("CopyToClipboardRecordSeperator");
                if (recordSep != null)
                {
                    foreach (ComboBoxSeperator sep in comboBoxRecordSeperator.Items)
                    {
                        if (sep.Value == recordSep)
                        {
                            comboBoxRecordSeperator.SelectedItem = sep;
                            break;
                        }
                    }
                }
                else
                {
                    comboBoxRecordSeperator.SelectedIndex = 0;
                }

                checkBoxFieldsInFirstLine.Checked = Convert.ToBoolean(regKey.GetValue("CopyToClipboardFieldsInFirstLine", true));
                checkBoxQuoteTextFields.Checked   = Convert.ToBoolean(regKey.GetValue("CopyToClipboardQuoteTextFields", false));
            }

            chooseFieldControl.Init(dataBase, copyTracks ? FieldType.TrackAndCD : FieldType.CD, selectedFields);
            chooseFieldControl.SelectionChanged += new ChooseFieldControl.SelectionChangedDelegate(chooseFieldControl_SelectionChanged);
        }
コード例 #12
0
ファイル: Helper.cs プロジェクト: SyAbou/sharpointonline
        public static List EnsurePortalConfigList(Web web)
        {
            List list = null;

            try
            {
                Logger.LogInfoMessage(String.Format("Ensuring Portal Config list for {0} ...", web.Url), true);

                list = web.GetListByUrl(Constants.ConfigurationListWebRelativeUrl);
                if (list == null)
                {
                    Logger.LogInfoMessage(String.Format("Creating Portal Config list ..."), true);
                    list = web.CreateList(Microsoft.SharePoint.Client.ListTemplateType.GenericList, Constants.ConfigurationListTitle, false, true, Constants.ConfigurationListWebRelativeUrl, false);
                }

                FieldCollection     fields      = list.Fields;
                View                defaultView = list.DefaultView;
                ViewFieldCollection viewFields  = defaultView.ViewFields;
                web.Context.Load(fields);
                web.Context.Load(defaultView);
                web.Context.Load(viewFields);
                web.Context.ExecuteQueryRetry();

                Logger.LogInfoMessage(String.Format("- Ensuring List Field [{0}] ...", Constants.PnPConfigKey_DisplayName), false);
                if (list.FieldExistsById(new Guid(Constants.PnPConfigKey_GUID)) == false)
                {
                    fields.Add(web.GetFieldById <Field>(new Guid(Constants.PnPConfigKey_GUID), true));
                    viewFields.Add(Constants.PnPConfigKey_InternalName);
                    defaultView.Update();
                }
                Logger.LogInfoMessage(String.Format("- Ensuring List Field [{0}] ...", Constants.PnPConfigValue_DisplayName), false);
                if (list.FieldExistsById(new Guid(Constants.PnPConfigValue_GUID)) == false)
                {
                    fields.Add(web.GetFieldById <Field>(new Guid(Constants.PnPConfigValue_GUID), true));
                    viewFields.Add(Constants.PnPConfigValue_InternalName);
                    defaultView.Update();
                }
                string viewQuery = String.Format(Constants.ListViewQueryFormatString, Constants.PnPConfigKey_InternalName);
                if (!defaultView.ViewQuery.Equals(viewQuery, StringComparison.InvariantCultureIgnoreCase))
                {
                    defaultView.ViewQuery = viewQuery;
                    defaultView.Update();
                }
                list.Update();
                web.Context.ExecuteQueryRetry();

                //Initialize the list
                ListItemCollection listItems = list.GetItems(CamlQuery.CreateAllItemsQuery());
                web.Context.Load(listItems);
                web.Context.ExecuteQueryRetry();

                // Initialize the list only if it is empty.
                if (listItems.Count == 0)
                {
                    Logger.LogInfoMessage(String.Format("Initializing Portal Config list ..."), false);

                    Logger.LogInfoMessage(String.Format("- Adding list item..."), false);

                    ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
                    ListItem listItem = list.AddItem(itemCreateInfo);

                    listItem["Title"] = Constants.ConfigurationListFooterKey;
                    listItem[Constants.PnPConfigKey_InternalName]   = Constants.ConfigurationListFooterKey;
                    listItem[Constants.PnPConfigValue_InternalName] = String.Format(
                        "<table border='0' cellpadding='0' cellspacing='0' align='center'>" +
                        "<tbody style='float:right;'>" +
                        "<tr>" +
                        "<td align='center' style=''>" +
                        "<a href='{0}' style='color: white'>Footer 1</a> | " +
                        "<a href='{0}' style='color: white'>Footer 2</a> | " +
                        "<a href='{0}' style='color: white'>Footer 3</a> | " +
                        "<a href='{0}' style='color: white'>Footer 4</a> | " +
                        "<a href='{0}' style='color: white'>Footer 5</a> " +
                        "</td>" +
                        "</tr>" +
                        "<tr>" +
                        "<td align='center' style=''>" +
                        "{1} Contoso, Inc. All Rights Reserved." +
                        "</td>" +
                        "</tr>" +
                        "</tbody>" +
                        "</table>", Constants.FooterNavLinkUrl, DateTime.Now.Year);

                    listItem.Update();
                    web.Context.ExecuteQueryRetry();
                }
                Logger.LogSuccessMessage(String.Format("Ensured Portal Config list for {0}", web.Url), false);
            }
            catch (Exception ex)
            {
                Logger.LogErrorMessage(String.Format("EnsurePortalConfigList() failed for {0}: Error={1}", web.Url, ex.Message), false);
            }

            return(list);
        }
コード例 #13
0
 public void AddField(IField field)
 {
     _fields.Add(field);
 }
コード例 #14
0
 public ManualPoint AddField(string key, int value)
 {
     _fields.Add(key, value);
     return(this);
 }
        /// <summary>
        /// Save extension field serilized into extension field (ExtensionData)
        /// </summary>
        /// <param name="extensionObject"></param>
        public void Serialize(IExtensionObject extensionObject)
        {
            FieldCollection fieldValues = new FieldCollection();
            IEnumerator<KeyValuePair<string, object>> fieldNameValueEnumerator = extensionObject.GetFieldEnumerator();
            while (fieldNameValueEnumerator.MoveNext())
            {
                KeyValuePair<string, object> fieldNameValuePair = fieldNameValueEnumerator.Current;

                using (ValidationScope validationScope = new ValidationScope())
                {
                    try
                    {
                        IFieldValue fieldValue = ConvertToFieldValueInterface(extensionObject.ExtensionDataTypeId, fieldNameValuePair.Key, fieldNameValuePair.Value);
                        if (fieldValue != null) fieldValues.Add(new FieldNameValuePair(fieldNameValuePair.Key, fieldValue));
                    }
                    catch (InvalidFieldValueException exp)
                    {
                        validationScope.Error(exp.Message);
                    }
                    catch (NotSupportedException exp)
                    {
                        validationScope.Error(exp.Message);
                    }
                }
            }

            StringBuilder output = new StringBuilder();

            XmlWriterSettings settings = new XmlWriterSettings()
            {
                Encoding = Encoding.UTF8,
                Indent = true
            };

            using (XmlWriter writer = XmlWriter.Create(output, settings))
            {
                serializer.WriteObject(writer, fieldValues);
            }

            extensionObject.ExtensionData = output.ToString();
        }
コード例 #16
0
        public FormPrintCatalog(DataBase db)
        {
            InitializeComponent();

            dataBase = db;

            cdListFields.Add(new ColumnField(Field.ArtistCDName));
            cdListFields.Add(new ColumnField(Field.Title));
            cdListFields.Add(new ColumnField(Field.NumberOfTracks));
            cdListFields.Add(new ColumnField(Field.TotalLength));

            detailListFields.Add(Field.ArtistCDName);
            detailListFields.Add(Field.Title);
            detailListFields.Add(Field.ComposerCDName);
            detailListFields.Add(Field.NumberOfTracks);
            detailListFields.Add(Field.TotalLength);
            detailListFields.Add(Field.Sampler);
            detailListFields.Add(Field.Category);
            detailListFields.Add(Field.Medium);
            detailListFields.Add(Field.Date);
            detailListFields.Add(Field.Codes);
            detailListFields.Add(Field.Price);
            detailListFields.Add(Field.User1);
            detailListFields.Add(Field.User2);
            detailListFields.Add(Field.User3);
            detailListFields.Add(Field.User4);
            detailListFields.Add(Field.User5);

            trackListFields.Add(new ColumnField(Field.ArtistTrackName));
            trackListFields.Add(new ColumnField(Field.TrackTitle));
            trackListFields.Add(new ColumnField(Field.TrackLength));

            trackDetailsListFields.Add(new ColumnField(Field.TrackNumber));
            trackDetailsListFields.Add(new ColumnField(Field.ArtistTrackName));
            trackDetailsListFields.Add(new ColumnField(Field.TrackTitle));
            trackDetailsListFields.Add(new ColumnField(Field.TrackLength));

            cdListFields           = ColumnFieldCollection.LoadFromRegistry("PrintCDListFields", cdListFields);
            trackListFields        = ColumnFieldCollection.LoadFromRegistry("PrintTrackListFields", trackListFields);
            trackDetailsListFields = ColumnFieldCollection.LoadFromRegistry("PrintTrackDetailsListFields", trackDetailsListFields);

            cdSortFields.Add(new SortField(Field.ArtistCDName));
            cdSortFields.Add(new SortField(Field.Title));

            trackSortFields.Add(new SortField(Field.ArtistTrackName));
            trackSortFields.Add(new SortField(Field.TrackTitle));

            headerFont  = new Font("Arial", 10, FontStyle.Bold);
            detailBrush = Brushes.Black;

            toolStripComboBoxZoom.Items.Add(new ZoomLevel(10));
            toolStripComboBoxZoom.Items.Add(new ZoomLevel(25));
            toolStripComboBoxZoom.Items.Add(new ZoomLevel(50));
            toolStripComboBoxZoom.Items.Add(new ZoomLevel(75));
            toolStripComboBoxZoom.Items.Add(new ZoomLevel(100));
            toolStripComboBoxZoom.Items.Add(new ZoomLevel(125));
            toolStripComboBoxZoom.Items.Add(new ZoomLevel(150));
            toolStripComboBoxZoom.Items.Add(new ZoomLevel(200));
            toolStripComboBoxZoom.Items.Add(new ZoomLevel(300));
            toolStripComboBoxZoom.Items.Add(new ZoomLevel(400));
            toolStripComboBoxZoom.Items.Add(new ZoomLevel(ZoomType.WholePage));
            toolStripComboBoxZoom.SelectedIndex = 10;

            radioButtonCDList.Checked         = true;
            checkBoxHeaderPrintSort.Checked   = Settings.Current.PrintHeaderSort;
            checkBoxHeaderPrintFilter.Checked = Settings.Current.PrintHeaderFilter;
            checkBoxHeaderPrintDate.Checked   = Settings.Current.PrintHeaderDate;
        }
コード例 #17
0
ファイル: Cursor.cs プロジェクト: subTee/DSInternals
        /// <summary>
        /// Gets the fields of the current row.
        /// </summary>
        /// <param name="grbit">The grbit.</param>
        /// <returns>A <see cref="FieldCollection"/> object to allow retrieval of all fields of the current row.</returns>
        internal FieldCollection GetFields(RetrieveColumnGrbit grbit)
        {
            JET_PFNREALLOC allocator =
                (context, pv, cb) =>
                IntPtr.Zero == pv ? Marshal.AllocHGlobal(new IntPtr(cb)) : Marshal.ReAllocHGlobal(pv, new IntPtr(cb));

            lock (this.isamSession)
            {
                this.CheckDisposed();
                this.CheckRecord();

                EnumerateColumnsGrbit enumerateGrbit = ((grbit & RetrieveColumnGrbit.RetrieveCopy) != 0)
                                                           ? EnumerateColumnsGrbit.EnumerateCopy
                                                           : EnumerateColumnsGrbit.None;

                using (IsamTransaction trx = new IsamTransaction(this.isamSession, true))
                {
                    // enumerate all field values in the current record or copy
                    // buffer
                    JET_ENUMCOLUMN[] jecs;
                    int numColumnValues;
                    Api.JetEnumerateColumns(
                        this.isamSession.Sesid,
                        this.tableid,
                        0, // numColumnids
                        null, // columnids
                        out numColumnValues,
                        out jecs,
                        allocator,
                        IntPtr.Zero, // allocatorContext,
                        int.MaxValue,
                        enumerateGrbit);

                    // create a field collection to contain our field values
                    FieldCollection fields = new FieldCollection();

                    // save the location of the source record for these field values
                    fields.Location = this.Location;

                    // fill the field collection with our field values
                    if (jecs != null && jecs.Length > 0)
                    {
                        foreach (JET_ENUMCOLUMN jec in jecs)
                        {
                            if (jec.rgEnumColumnValue != null && jec.rgEnumColumnValue.Length > 0)
                            {
                                JET_COLUMNBASE columnbase;
                                VistaApi.JetGetTableColumnInfo(
                                    this.isamSession.Sesid,
                                    this.tableid,
                                    jec.columnid,
                                    out columnbase);

                                Columnid columnid = new Columnid(columnbase);
                                bool isAscii = columnbase.cp == JET_CP.ASCII;
                                FieldValueCollection values = new FieldValueCollection(columnid);
                                foreach (JET_ENUMCOLUMNVALUE jecv in jec.rgEnumColumnValue)
                                {
                                    // FUTURE-2013/11/15-martinc: Drat, this is an IntPtr, and ObjectFromBytes() really
                                    // wants a byte[] array. Copying the data to a byte array just to simply
                                    // re-interpret it as an object is inefficient.
                                    // We should write Converter.ObjectFromIntPtr...
                                    byte[] bytesData = new byte[jecv.cbData];
                                    Marshal.Copy(jecv.pvData, bytesData, 0, bytesData.Length);

                                    values.Add(Converter.ObjectFromBytes(columnbase.coltyp, isAscii, bytesData));
                                }

                                values.ReadOnly = true;
                                fields.Add(values);
                            }
                        }
                    }

                    fields.ReadOnly = true;

                    // Return the field collection.
                    return fields;
                }
            }
        }
コード例 #18
0
        /// <summary>
        /// Cria um valor compatível para o tipo indicado com base no conteúdo
        /// do modelo deserializado.
        /// </summary>
        /// <param name="type">O tipo do dado esperado.</param>
        /// <param name="node">O modelo deserializado.</param>
        /// <returns>O valor obtido da compatibilização.</returns>
        private object CreateCompatibleValue(Type type, NodeModel node)
        {
            if (node == null)
            {
                return(null);
            }

            if (type == typeof(PropertyCollection))
            {
                return((PropertyCollection)CreateCompatibleValue(typeof(object), node));
            }

            if (type == typeof(NameCollection))
            {
                var target = new NameCollection();
                foreach (var item in node.ChildValues())
                {
                    target.Add(item.Value.ToString());
                }
                return(target);
            }

            if (type == typeof(FieldCollection))
            {
                var target = new FieldCollection();
                foreach (var @object in node.ChildObjects())
                {
                    var field = new Field();
                    CopyNodeProperties(@object, field);
                    target.Add(field);
                }
                return(target);
            }

            if (type == typeof(FieldProperties))
            {
                var properties = new FieldProperties();
                CopyNodeProperties(node, properties);
                return(properties);
            }

            if (type == typeof(LinkCollection))
            {
                var target = new LinkCollection();
                foreach (var item in node.Children())
                {
                    var link = new Link();
                    CopyNodeProperties(item, link);
                    target.Add(link);
                }
                return(target);
            }

            if (type == typeof(EntityActionCollection))
            {
                var target = new EntityActionCollection();
                foreach (var item in node.Children())
                {
                    var action = new EntityAction();
                    CopyNodeProperties(item, action);
                    target.Add(action);
                }
                return(target);
            }

            if (type == typeof(EntityCollection))
            {
                var target = new EntityCollection();
                foreach (var item in node.Children())
                {
                    var entity = new Entity();
                    CopyNodeProperties(item, entity);
                    target.Add(entity);
                }
                return(target);
            }

            if (type == typeof(CaseVariantString))
            {
                var text = (node as ValueModel)?.Value.ToString();
                return(text.ChangeCase(TextCase.PascalCase));
            }

            return(CreateCompatibleValue(node));
        }