예제 #1
0
        public virtual async Task <long> Add(BenchmarkResultDto entity)
        {
            var newEntity = new Result()
            {
                BenchmarkId     = entity.BenchmarkId,
                Browser         = entity.Browser,
                DevicePlatform  = entity.DevicePlatform,
                OperatingSystem = entity.OS,
                RawUastring     = entity.RawUserAgenString,
                UserId          = entity.UserId,
                ResultRow       = new List <ResultRow>(),
                Version         = entity.BenchmarkVersion,
                Created         = DateTime.UtcNow
            };

            foreach (var row in entity.ResultRows)
            {
                var dbrow = new ResultRow()
                {
                    ExecutionsPerSecond   = row.ExecutionsPerSecond,
                    TestName              = row.TestName,
                    NumberOfSamples       = row.NumberOfSamples,
                    RelativeMarginOfError = row.RelativeMarginOfError
                };
                newEntity.ResultRow.Add(dbrow);
            }

            this.Validate(newEntity);

            this.m_db.Result.Add(newEntity);
            await this.m_db.SaveChangesAsync().ConfigureAwait(false);

            return(newEntity.Id);
        }
예제 #2
0
        public static void CopyValuesFrom(this object dest, ResultRow source, Action <Exception> onError = null)
        {
            if ((dest == null) || (source == null))
            {
                return;
            }


            var writableProps = dest.GetType().WritableProps();

            foreach (var key in source.Keys)
            {
                var prop = writableProps.SingleOrDefault(x
                                                         => x.Name.ToLower() == key.ToLower());
                if (prop != null)
                {
                    //try   { prop.SetValue(dest, source[key], null); }
                    //catch (Exception ex){ onError?.Invoke(ex); }
                    if (prop.PropertyType == typeof(int))
                    {
                        try   { prop.SetValue(dest, Convert.ToInt32(source[key]), null); }
                        catch (Exception ex) { onError?.Invoke(ex); }
                    }
                    else
                    {
                        try   { prop.SetValue(dest, source[key], null); }
                        catch (Exception ex) { onError?.Invoke(ex); }
                    }
                }
            }
        }
예제 #3
0
        public static void FillRow(Object obj, out SqlInt32 BuildId, out SqlInt32 Price)
        {
            ResultRow selectResults = (ResultRow)obj;

            BuildId = selectResults.BuildId;
            Price   = selectResults.Price;
        }
예제 #4
0
 public StoreableDatabaseObject(ResultRow row)
 {
     if (row != null)
     {
         LoadFromDatabase(row);
     }
 }
예제 #5
0
        public void CreateBackup()
        {
            ResultTable table = Mysql.Query("SELECT * FROM `shaiya_mob_db`");

            if (table.Rows.Count == 0)
            {
                return;
            }

            string savePath = AppDomain.CurrentDomain.BaseDirectory + "Backup\\MobDB_" + DateTime.Now.ToString().Replace('.', '_').Replace(':', '_') + ".sql";

            System.IO.Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "Backup\\");
            System.IO.FileInfo info = new System.IO.FileInfo(savePath);
            using (System.IO.TextWriter writer = info.CreateText()) {
                writer.WriteLine("TRUNCATE TABLE `shaiya_mob_db`;");
                writer.WriteLine("INSERT INTO `shaiya_mob_db` ( `id`, `pos_x`, `pos_y`, `name`, `mapname`, `level`, `anzahl`, `element`, `boss`, `info` ) VALUES");
                for (int i = 0; i < table.Rows.Count; i++)
                {
                    ResultRow row = table.Rows[i];
                    writer.Write("( " + row["id"].GetInt() + ", " + row["pos_x"].GetInt() + ", " + row["pos_y"].GetInt() + ", '" + row["name"].GetString() + "', '" + row["mapname"].GetString() + "', '" + row["level"].GetString() + "', '" + row["anzahl"].GetString() + "', '" + row["element"].GetString() + "', " + row["boss"].GetByte() + ", '" + row["info"].GetString() + "' )");
                    if (i < table.Rows.Count - 1)
                    {
                        writer.WriteLine(",");
                    }
                }
                writer.WriteLine(";");
            }
        }
예제 #6
0
        /// <inheritdoc />
        public async Task <ResultSet <T> > SelectAsync <T>(string query, Dictionary <string, dynamic> bindings = null) where T : Model <T>, new()
        {
            using var connection = new Connection(ConnectionString);
            await connection.OpenAsync();

            using var command = new Command(query, connection);
            BindParameters(command, bindings);

            using var reader = await command.ExecuteReaderAsync();

            ResultSet <T> resultSet = new ResultSet <T>();

            if (Manager.DebugMode)
            {
                Manager.Logger(query);
            }

            while (await reader.ReadAsync())
            {
                ResultRow <T> resultRow = new ResultRow <T>();

                for (int column = 0; column < reader.FieldCount; column++)
                {
                    resultRow.Columns.Add(reader.GetName(column), reader.GetValue(column));
                }

                resultSet.Rows.Add(resultRow);
            }

            return(resultSet);
        }
예제 #7
0
        public static void handleRequest(string pluginid, Connector conn, ref Misc.PageElements pageElements, HttpRequest request, HttpResponse response)
        {
            // Add headers - CSS and JS
            if (pageElements["HEADER"] == null)
            {
                pageElements["HEADER"] = string.Empty;
            }
            pageElements["HEADER"] += "<link href=\"" + pageElements["URL"] + "/Content/CSS/CC128.css\" type=\"text/css\" rel=\"Stylesheet\" />";
            pageElements["HEADER"] += "<script src=\"" + pageElements["URL"] + "/Content/JS/CC128.js\"></script>";
            // Determine which page the user wants
            string subPage = request.QueryString["1"];

            if (subPage != null && subPage == "history")
            {
                pageHistory(pluginid, conn, ref pageElements, request, response);
            }
            else if (subPage == "ajax")
            {
                // Write the last watt reading
                ResultRow lastReading = conn.Query_Read("SELECT (SELECT watts FROM cc128_readings WHERE datetime >= DATE_SUB(NOW(), INTERVAL 24 HOUR) ORDER BY datetime DESC LIMIT 1) AS last_reading, (SELECT MAX(watts) FROM cc128_readings WHERE datetime >= DATE_SUB(NOW(), INTERVAL 24 HOUR)) AS max_watts")[0];
                response.ContentType = "text/xml";
                response.Write("<d><w>" + lastReading["last_reading"] + "</w><m>" + lastReading["max_watts"] + "</m></d>");
                conn.Disconnect();
                response.End();
            }
            else
            {
                pagePower(pluginid, conn, ref pageElements, request, response);
            }
            // Set the base content
            pageElements["TITLE"]   = "CC128 Energy Monitor - <!--CC128_TITLE-->";
            pageElements["CONTENT"] = Core.templates["cc128"]["base"];
        }
예제 #8
0
        protected virtual void FillResult(MySqlDataReader reader, out List <IResultRow> rows)
        {
            IReadOnlyDictionary <ITableDescriptor, IReadOnlyCollection <IColumnDescriptor> > Filters = Context.Filters;

            rows = new List <IResultRow>();
            while (reader.Read())
            {
                IResultRowInternal NewResult = new ResultRow();

                foreach (KeyValuePair <ITableDescriptor, IReadOnlyCollection <IColumnDescriptor> > Entry in Filters)
                {
                    ITableDescriptor Table = Entry.Key;
                    IEnumerable <IColumnDescriptor> ColumnFilter = Entry.Value;

                    foreach (IColumnDescriptor Column in ColumnFilter)
                    {
                        string TableName  = Table.Name;
                        string ColumnName = Column.Name;
                        string ResultName = TableName + "_" + ColumnName;

                        int Index = reader.GetOrdinal(ResultName);
                        if (reader.IsDBNull(Index))
                        {
                            continue;
                        }

                        object ConvertedValue = reader[ResultName];
                        NewResult.AddResult(Column, ConvertedValue);
                    }
                }

                rows.Add(NewResult);
            }
        }
예제 #9
0
        private ResultRow GetResultRow(IEnumerable <RowData> rowDatas, bool byProtein)
        {
            ResultRow resultRow        = null;
            var       rowDatasByCohort = new Dictionary <CohortKey, IList <RowData> >();

            foreach (var rowData in rowDatas)
            {
                if (resultRow == null)
                {
                    var peptide = Workspace.Peptides.GetChild(rowData.PeptideId);
                    resultRow = new ResultRow
                    {
                        PeptideSequence    = byProtein ? null : peptide.FullSequence,
                        ProteinDescription = peptide.ProteinDescription,
                        ProteinName        = peptide.ProteinName,
                        ProteinKey         = peptide.GetProteinKey(),
                    };
                }
                IList <RowData> list;
                if (!rowDatasByCohort.TryGetValue(rowData.CohortKey, out list))
                {
                    list = new List <RowData>();
                    rowDatasByCohort.Add(rowData.CohortKey, list);
                }
                list.Add(rowData);
            }
            foreach (var entry in rowDatasByCohort)
            {
                resultRow.ResultDatas.Add(entry.Key, GetResultData(entry.Value));
            }
            return(resultRow);
        }
예제 #10
0
        private void DrawRow(ResultRow dependency)
        {
            using (new EditorGUILayout.VerticalScope(EditorStyles.helpBox))
            {
                using (new EditorGUILayout.HorizontalScope())
                {
                    if (GUILayout.Button(dependency.LabelContent, Style.Instance.RowMainAssetBtn))
                    {
                        if (_click.IsDoubleClick(dependency.Main))
                        {
                            Selection.activeObject = dependency.Main;
                        }
                        else
                        {
                            EditorGUIUtility.PingObject(dependency.Main);
                        }

                        _click = new PrevClick(dependency.Main);
                    }
                    if (GUILayout.Button(Style.Instance.LookupBtn.Content, Style.Instance.LookupBtn.Style))
                    {
                        _postponedActions.Add(() =>
                                              Init(_data.Nest(dependency.Main)));
                    }
                }
                dependency.SerializedObject.Update();
                EditorGUI.BeginChangeCheck();
                if (dependency.Target)
                {
                    foreach (var prop in dependency.Properties)
                    {
                        using (new EditorGUILayout.HorizontalScope())
                        {
                            var locked = prop.Property.objectReferenceValue is MonoScript;
                            var f      = GUI.enabled;

                            if (locked)
                            {
                                GUI.enabled = false;
                            }

                            EditorGUILayout.LabelField(prop.Content, Style.Instance.RowLabel, GUILayout.MaxWidth(_labelMaxWidth));
                            EditorGUILayout.PropertyField(prop.Property, GUIContent.none, true, GUILayout.MinWidth(_rowPropWidth));

                            if (locked)
                            {
                                GUI.enabled = f;
                            }
                        }
                    }
                }

                if (EditorGUI.EndChangeCheck())
                {
                    dependency.SerializedObject.ApplyModifiedProperties();
                }
            }
        }
예제 #11
0
            public async Task <Response> Handle(Request request, CancellationToken token)
            {
                List <ResultRow> resultRows = new List <ResultRow>();

                string saveHtmlPath = @"D:\temp\output\adbGoodsConsulting";

                int pageFrom = 1;
                int pageMax  = 177;
                int pageSize = 20;

                for (int page = pageFrom; page <= pageMax; page++)
                {
                    string path       = Path.Combine(saveHtmlPath, $"page-{page}.html");
                    var    originRows = await CrawlerMaster(path);

                    int count = originRows.Count();
                    for (int j = 0; j < originRows.Count(); j++)
                    {
                        var      originRow = originRows.ElementAt(j);
                        string[] summaries = originRow.Summary.Split(";");
                        var      row       = new ResultRow()
                        {
                            Id                  = (page - 1) * pageSize + j + 1,
                            Group               = "Consulting",
                            ProjectCountry      = ConvertCountryString(summaries[1]),
                            ExecutingAgency     = originRow.ExecutingAgency,
                            ContractorName      = originRow.ContractorName,
                            ContractorCountry   = ConvertCountryString(originRow.ContractorAddress),
                            TotalContractAmount = originRow.TotalContractAmount != null?Convert.ToDecimal(originRow.TotalContractAmount.Replace(",", "")) : 0,
                                                      FinancedByAdb = originRow.FinancedByAdb != null?Convert.ToDecimal(originRow.FinancedByAdb.Replace(",", "")) : 0
                        };
                        if (summaries.Count() == 3)
                        {
                            if (summaries[2].Trim().StartsWith("Contract date:") == false)
                            {
                                row.ProjectDate = ConvertToDateString(summaries[2].Replace("Contract date:", "").Trim());
                            }
                            else
                            {
                                row.Sector = summaries[2].Trim();
                            }
                        }
                        else if (summaries.Count() > 3)
                        {
                            row.Sector      = summaries[2].Trim();
                            row.ProjectDate = ConvertToDateString(summaries[3].Replace("Contract date:", "").Trim());
                        }
                        resultRows.Add(row);
                    }
                }

                await File.WriteAllTextAsync(@"D:\temp\output\result.txt", JsonConvert.SerializeObject(resultRows));

                return(new Response()
                {
                    Result = resultRows
                });
            }
예제 #12
0
            static object OrderSelector(Expression expression, ResultRow row)
            {
                if (!(expression.Value is Expression.Identifier identifier))
                {
                    throw new NotSupportedException("Worker can't execute expressions, this should have been projected for the underlying query to handle");
                }

                return(row.Fields.TryGetValue(identifier.Name, out var value) ? value : null);
            }
 public ResultTableStructure(string name, int columnNumber, int rowsNumber, string[] headers)
 {
     DbName = name;
     Rows   = new ResultRow[rowsNumber];
     for (int i = 0; i < rowsNumber; i++)
     {
         Rows[i] = new ResultRow(columnNumber, i == 0, i == 0 ? headers : null);
     }
 }
예제 #14
0
        public void ResultRow_UnchangeGain_Call()
        {
            ResultRow rr = new ResultRow("061790", "2017/12/20",
                                         570, 560, 570, 1000000, 10, "TSE.TW", "加權指數", 1053274,
                                         1052237);
            float gain = rr.GetUnchangeGain();

            Assert.AreEqual("061790", rr.WarrantID);
        }
예제 #15
0
        public void ResultRow_UnchangeGain_Put()
        {
            ResultRow rr = new ResultRow("04144P", "2018/07/03",
                                         220, 215, 215, 11448, 156, "2317.TW", "鴻海", 10575,
                                         10650);
            float gain = rr.GetUnchangeGain();

            Assert.AreEqual("04144P", rr.WarrantID);
        }
예제 #16
0
        // Generates result row.
        public void FormResultRow(string compare)
        {
            ResultRow row = new ResultRow();

            row.Number = stepCount;
            row.SetStack(stack);
            row.Symbol = compare;
            row.SetInputChain(inputChain);
            ResultTable.Add(row);
        }
예제 #17
0
 private bool MapValues(IMapOverride overrider, ResultRow row, T repoNode)
 {
     try {
         return(DbRowMapper.Map(row, repoNode, overrider));
     }
     catch (Exception ex) {
         return(LogError("DbRowMapper.Map", ex));
     }
     //Debug_n("DbRowMapper.Map success", "");
 }
예제 #18
0
        /// <summary>
        /// Executes the query.
        /// </summary>
        /// <param name="maxRows">
        /// The maximum rows.
        /// </param>
        /// <returns>
        /// The <see cref="ResultCollection"/>.
        /// </returns>
        public virtual ResultCollection ExecuteQuery(int maxRows)
        {
            ResultCollection results;
            IntPtr           stmt = IntPtr.Zero;

            try
            {
                stmt = this.Prepare();
                var cols = new ColumnInfoExt[SQLite3.ColumnCount(stmt)];

                for (var i = 0; i < cols.Length; i++)
                {
                    cols[i] = new ColumnInfoExt {
                        Name = SQLite3.ColumnName16(stmt, i), ColumnIndex = i
                    };
                }

                results = new ResultCollection(cols);

                var rows = 0;
                while (SQLite3.Step(stmt) == SQLite3.Result.Row)
                {
                    var obj = new ResultRow();
                    for (var i = 0; i < cols.Length; i++)
                    {
                        if (cols[i] == null)
                        {
                            continue;
                        }

                        var colType = SQLite3.ColumnType(stmt, i);
                        cols[i].ColumnMainType = colType;

                        var val = this.ReadCol(stmt, i, colType, cols[i].ColumnClrType);
                        obj[cols[i].ColumnIndex] = val;
                    }

                    results.Add(obj);

                    if (maxRows != 0 && ++rows == maxRows)
                    {
                        break;
                    }
                }
            }
            finally
            {
                if (stmt != IntPtr.Zero)
                {
                    SQLite3.Finalize(stmt);
                }
            }

            return(results);
        }
예제 #19
0
        public void AddResult(SystemResult result)
        {
            var row = new ResultRow(myRankingSection, result);

            row["Stock"]              = result.Stock;
            row["Signal"]             = new ValueWithDetails(result.Signal, new DetailedReportAdapter(result.Stock.Isin, result.Report));
            row["Gain/Risk ratio"]    = result.GainRiskRatio;
            row["Expected gain"]      = result.ExpectedGain;
            row["Historical signals"] = GetHistoricalSignals(result);

            myRankingSection.Rows.Add(row);
        }
예제 #20
0
        static void LadderCalculator(Competition competition, Team team, ResultRow resultRow)
        {
            var fixtures          = competition.Fixtures.Where(f => f.Status == FixtureStatus.Finished && (f.TeamHome == team || f.TeamVisitor == team)).ToList();
            var totalGoalsFor     = 0;
            var totalGoalsAgainst = 0;
            var totalWins         = 0;
            var totalLoses        = 0;
            var totalDraws        = 0;

            foreach (var fix in fixtures)
            {
                if (fix.TeamHome == team)
                {
                    totalGoalsFor     += fix.TeamHomeScore;
                    totalGoalsAgainst += fix.TeamVisitorScore;
                    if (fix.TeamHomeScore > fix.TeamVisitorScore)
                    {
                        totalWins++;
                    }
                    else if (fix.TeamHomeScore < fix.TeamVisitorScore)
                    {
                        totalLoses++;
                    }
                    else
                    {
                        totalDraws++;
                    }
                }
                else
                {
                    totalGoalsFor     += fix.TeamVisitorScore;
                    totalGoalsAgainst += fix.TeamHomeScore;
                    if (fix.TeamHomeScore > fix.TeamVisitorScore)
                    {
                        totalLoses++;
                    }
                    else if (fix.TeamHomeScore < fix.TeamVisitorScore)
                    {
                        totalWins++;
                    }
                    else
                    {
                        totalDraws++;
                    }
                }
            }
            resultRow.GoalsAgainst = totalGoalsAgainst;
            resultRow.GoalsFor     = totalGoalsFor;
            resultRow.Wins         = totalWins;
            resultRow.Loses        = totalLoses;
            resultRow.Draws        = totalDraws;
            resultRow.Matches      = fixtures.Count();
        }
예제 #21
0
        private void queryReadInteral(ref Result result, ref MySqlCommand command)
        {
            // Create reader
            MySqlDataReader reader = command.ExecuteReader();

            // Read row-by-row
            byte[]       buffer;
            MemoryStream bufferMS;
            int          bufferOffset;
            int          bytesAvailable;
            ResultRow    row;
            int          t;

            while (reader.Read())
            {
                row = new ResultRow();
                for (t = 0; t < reader.FieldCount; t++)
                {
                    row.attributes.Add(reader.GetName(t), reader.IsDBNull(t) ? null : reader.GetValue(t));
                    // Check if the column of the row is a byte-array, if so -> add to separate byte dictionary
                    string dt = reader.GetDataTypeName(t);
                    if (dt == "BLOB" || dt == "TINYBLOB" || dt == "MEDIUMBLOB" || dt == "LONGBLOB")
                    {
                        bufferMS = new MemoryStream();
                        try
                        {
                            bufferOffset   = 0;
                            bytesAvailable = (int)reader.GetBytes(t, 0, null, 0, 0);
                            while (bufferOffset < bytesAvailable)
                            {
                                reader.GetBytes(t, bufferOffset, buffer = new byte[BYTE_BUFFER_SIZE], 0, BYTE_BUFFER_SIZE);
                                bufferMS.Write(buffer, 0, BYTE_BUFFER_SIZE);
                                bufferOffset += BYTE_BUFFER_SIZE;
                            }
                            bufferMS.Flush();
                            if (row.attributesByteArray == null)
                            {
                                row.attributesByteArray = new Dictionary <string, byte[]>();
                            }
                            row.attributesByteArray.Add(reader.GetName(t), bufferMS.ToArray());
                        }
                        catch { }
                        finally
                        {
                            bufferMS.Dispose();
                        }
                    }
                }
                result.tuples.Add(row);
            }
            reader.Close();
        }
예제 #22
0
        /// <summary>
        /// <paramref name="reader"/>를 읽어, <see cref="ResultRow"/>의 컬렉션인 <see cref="ResultSet"/>을 빌드합니다.
        /// </summary>
        /// <param name="reader">DataReader</param>
        /// <param name="nameMapper">컬럼명을 속성명으로 매핑해주는 매퍼입니다.</param>
        /// <param name="firstResult">첫번째 레코드 인덱스 (0부터 시작)</param>
        /// <param name="maxResults">최대 레코드 수</param>
        /// <returns><see cref="ResultSet"/> 인스턴스</returns>
        public static ResultSet CreateResultSet(this IDataReader reader, INameMapper nameMapper, int firstResult, int maxResults)
        {
            reader.ShouldNotBeNull("reader");

            if (nameMapper == null)
            {
                nameMapper = new SameNameMapper();
            }

            if (IsDebugEnabled)
            {
                log.Debug("IDataReader로부터 정보를 읽어 ResultRow들을 만들어 ResultSet 으로 빌드합니다...");
            }

            var resultSet = new ResultSet();

            while (firstResult-- > 0)
            {
                if (reader.Read() == false)
                {
                    return(resultSet);
                }
            }

            if (maxResults <= 0)
            {
                maxResults = int.MaxValue;
            }

            resultSet.FieldNames = reader.GetFieldNames();

            var rowIndex = 0;

            while (reader.Read() && rowIndex++ < maxResults)
            {
                var row = new ResultRow();

                foreach (var fieldName in resultSet.FieldNames)
                {
                    row.Add(nameMapper.MapToPropertyName(fieldName), reader.AsValue(fieldName));
                }

                resultSet.Add(row);
            }

            if (IsDebugEnabled)
            {
                log.Debug("IDataReader로부터 정보를 읽어 ResultSet을 빌드했습니다!!! Row Count=[{0}]", resultSet.Count);
            }

            return(resultSet);
        }
예제 #23
0
        void lvResult_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            ResultRow row = (ResultRow)lvResult.SelectedItem;

            if (row == null)
            {
                return;
            }

            ShowRow(row);

            e.Handled = true;
        }
예제 #24
0
        /// <summary>
        /// <paramref name="reader"/>를 읽어, <see cref="ResultRow"/>를 빌드합니다.
        /// </summary>
        /// <param name="reader">DataReader</param>
        /// <param name="fieldNames">컬럼명 리스트</param>
        /// <param name="nameMapper">컬럼명을 속성명으로 매핑해주는 매퍼입니다.</param>
        /// <returns></returns>
        internal static ResultRow CreateResultRow(this IDataReader reader, IList <string> fieldNames, INameMapper nameMapper)
        {
            Guard.Assert(reader.IsClosed == false, "reader 가 닫혀있습니다.");

            var row = new ResultRow();

            foreach (var fieldName in fieldNames)
            {
                row.Add(nameMapper.MapToPropertyName(fieldName), reader.AsValue(fieldName));
            }

            return(row);
        }
예제 #25
0
 public bool CheckDataRow(ResultRow r)
 {
     foreach (var eachAND in CNF.AND)
     {
         // eachAND.OR is a list of BooleanExpression
         var eachANDbool = (eachAND.OR).Any(c => (bool)c.Eval(r));
         if (!eachANDbool)
         {
             return(false);
         }
     }
     return(true);
 }
예제 #26
0
        protected override IEnumerable <ResultRow> Execute()
        {
            var row1 = new ResultRow();

            row1["CompanyName"] = "DynamicSoft";
            var row2 = new ResultRow();

            row2["CompanyName"] = "StaticSoft";

            return(new List <ResultRow> {
                row1, row2
            });
        }
예제 #27
0
        private bool IsFit()
        {
            ResultRow rr = this.GetCurrentRow() as ResultRow;

            IResultSet resultSet = (this.DataSource as SqlDataSource).Result as DevExpress.DataAccess.Sql.DataApi.IResultSet;
            ITable     tableProd = null;

            resultSet.TryGetTable("CategoryProducts", out tableProd);
            DevExpress.Data.Filtering.CriteriaOperator            filter    = DevExpress.Data.Filtering.CriteriaOperator.Parse(FilterExpression);
            DevExpress.Data.Filtering.Helpers.ExpressionEvaluator evaluator = new DevExpress.Data.Filtering.Helpers.ExpressionEvaluator((((ITypedList)tableProd).GetItemProperties(null)), filter);
            bool isFit = evaluator.Fit(rr);

            return(isFit);
        }
예제 #28
0
        public static List <ResultRow> BuildLadder(Competition competition, List <Team> teams)
        {
            var resultRows = new List <ResultRow>();

            foreach (var item in teams)
            {
                var resultRow = new ResultRow();
                resultRow.Team = item;
                LadderCalculator(competition, item, resultRow);
                resultRows.Add(resultRow);
            }

            return(resultRows.OrderByDescending(o => o.Points).ThenByDescending(o => o.Wins).ThenByDescending(o => o.Draws).ThenByDescending(o => o.GoalDifference).ThenByDescending(o => o.GoalsAgainst).ThenBy(o => o.Team.Name).ToList());
        }
예제 #29
0
        internal GLResultsTable(List<PerformanceCubeResult> resultsArray, DeviceTable deviceTable)
        {
            foreach (PerformanceCubeResult result in resultsArray)
            {
                int indexOfDevice = deviceTable.Find(result.DeviceDatabaseId, result.IsMonoTouch);
                if (indexOfDevice > -1)
                {
                    DeviceTable.DeviceForTable dft = deviceTable[indexOfDevice];
                    if (dft != null && dft.Checked)
                    {
                        bool insert = true;
                        int insertIndex = 0;
                        for (int i=0; i<this._resultRows.Count;i++)
                        {
                            if (_resultRows[i].NumTrangles == result.NumberOfTriangles)
                            {
                                insert = false;
                                insertIndex = i;
                                break;
                            }
                            else if (_resultRows[i].NumTrangles > result.NumberOfTriangles)
                            {
                                insertIndex = i;
                                break;
                            }
                            else if (i+1==_resultRows.Count)
                            {
                                insertIndex = _resultRows.Count;
                            }
                        }

                        ResultRow row;

                        if (insert)
                        {
                            row = new ResultRow (result.NumberOfTriangles, deviceTable.NuberOfDevices);
                            if (insertIndex < _resultRows.Count)
                                _resultRows.Insert (insertIndex, row);
                            else
                                _resultRows.Add (row);
                        }
                        else
                            row = _resultRows[insertIndex];

                        row[indexOfDevice] = result.FramesPerSecond;
                    }
                }
            }
        }
예제 #30
0
        public static T MapToDTO <T>(ResultRow row)
        {
            var myDict = new Dictionary <Type, Func <ResultRow, long, object> >()
            {
                { typeof(string), (rr, col) => rr.GetStringValue(col) },
                { typeof(int), (rr, col) => rr.GetIntegerValue(col) },
                { typeof(long), (rr, col) => rr.GetInt64Value(col) },
                { typeof(byte[]), (rr, col) => rr.GetBinaryValue(col) },
                { typeof(decimal), (rr, col) => rr.GetDecimalValue(col) },
                { typeof(double), (rr, col) => (double)rr.GetDecimalValue(col) },
                { typeof(float), (rr, col) => (float)rr.GetDecimalValue(col) },
                { typeof(DateTime?), (rr, col) =>
                  {
                      var time = rr.GetInt64Value(col);
                      if (time != 0)
                      {
                          return(DateTime.ParseExact(time.ToString(), "yyyyMMdd", CultureInfo.CurrentCulture));
                      }
                      return(null);
                  } },
                { typeof(bool), (rr, col) => rr.GetIntegerValue(col) == 1 }
            };

            var dto     = Activator.CreateInstance <T>();
            var myType  = typeof(T);
            var myProps = myType.GetProperties().ToList();

            foreach (var prop in myProps)
            {
                var customAttribute = prop.GetCustomAttribute <VismaBusinessColumnAttribute>();
                if (customAttribute != null)
                {
                    try
                    {
                        prop.SetValue(dto,
                                      myDict.ContainsKey(prop.PropertyType)
                                ? myDict[prop.PropertyType](row, customAttribute.ColumnId)
                                : null);
                    }
                    catch (Exception e)
                    {
                        //Most likely wrong prop type in DTO
                        throw;
                    }
                }
            }

            return(dto);
        }
예제 #31
0
        public void Case1()
        {
            var row = new ResultRow();
            row.Add("FirstName", "abc");
            row.Add("LastName", "def");

            var expctd = new SampleClass1
            {
                FirstName = "abc",
                LastName  = "def",
            };
            var actual = new SampleClass1();
            DbRowMapper.Map(row, actual).MustBe(true, "Map() ret val");
            actual.MustBe(expctd);
        }
예제 #32
0
        void OnNavigateClicked()
        {
            ResultRow row = (ResultRow)lvResult.SelectedItem;

            if (row == null)
            {
                return;
            }

            SetDirtySelectedItem();

            Entity entity = (Entity)Server.Convert(row.Entity, EntityType);

            OnNavigating(entity);
        }
예제 #33
0
        internal FLOPResultsTable(List<MatrixTestResult> resultsArray, DeviceTable deviceTable)
        {
            foreach (MatrixTestResult result in resultsArray)
            {
                int indexOfDevice = deviceTable.Find (result.DeviceDatabaseId);
                if (indexOfDevice > -1)
                {
                    ResultRow resultRow = _resultRows.Find ((e)=>{return e.DeviceId == result.DeviceDatabaseId;});

                    if (resultRow == null) {
                        resultRow = new ResultRow (result.DeviceDatabaseId);
                        _resultRows.Add (resultRow);
                    }

                    resultRow.AddResultInfo (result);
                }
            }
        }
예제 #34
0
 public static void pageArticle_View_Permissions(ref string pluginid, ref Connector conn, ref Misc.PageElements pageElements, ref HttpRequest request, ref HttpResponse response, ref bool permCreate, ref bool permDelete, ref bool permPublish, ref bool owner, ref StringBuilder content, ref ResultRow article)
 {
     if (!permPublish) return;
     // Check postback
     List<string> groupidsPostback = new List<string>();
     string field;
     for (int i = 0; i < request.Form.Count; i++)
     {
         field = request.Form.GetKey(i);
         if (field.StartsWith("group_") && field.Length > 6)
         {
             field = field.Substring(6);
             if (Misc.Plugins.isNumeric(field))
                 groupidsPostback.Add(field);
         }
     }
     bool updatedPerms = false;
     if (groupidsPostback.Count > 0)
     {
         // Update the permissions for the thread
         StringBuilder query = new StringBuilder();
         query.Append("DELETE FROM articles_thread_permissions WHERE threadid='").Append(Utils.Escape(article["threadid"])).Append("'; INSERT IGNORE INTO articles_thread_permissions (threadid, groupid) VALUES");
         string start = "('" + Utils.Escape(article["threadid"]) + "','";
         foreach (string groupid in groupidsPostback)
             query.Append(start).Append(groupid).Append("'),");
         query.Remove(query.Length - 1, 1).Append(";");
         conn.Query_Execute(query.ToString());
         updatedPerms = true;
     }
     // Generate user groups
     StringBuilder groups = new StringBuilder();
     foreach(ResultRow group in conn.Query_Read("SELECT g.groupid, g.title, (SELECT COUNT('') FROM articles_thread_permissions WHERE threadid='" + Utils.Escape(article["threadid"]) + "' AND groupid=g.groupid) AS access FROM bsa_user_groups AS g"))
         groups.Append(
             Core.templates["articles"]["permissions_usergroup"]
             .Replace("<GROUPID>", group["groupid"])
             .Replace("<TITLE>", HttpUtility.HtmlEncode(group["title"]))
             .Replace("<CHECKED>", group["access"] != "0" ? "checked" : string.Empty)
             );
     // Set content
     content.Append(
         Core.templates["articles"]["permissions"]
         .Replace("<SUCCESS>", updatedPerms ? Core.templates[pageElements["TEMPLATE"]]["success"].Replace("<SUCCESS>", "Successfully updated permissions!") : string.Empty)
         .Replace("<GROUPS>", groups.ToString())
         );
 }
예제 #35
0
 public static void pageArticle_View_Publish(ref string pluginid, ref Connector conn, ref Misc.PageElements pageElements, ref HttpRequest request, ref HttpResponse response, ref bool permCreate, ref bool permDelete, ref bool permPublish, ref bool owner, ref StringBuilder content, ref ResultRow article)
 {
     if (request.Form["confirm"] != null)
     {
         StringBuilder publishQuery = new StringBuilder();
         publishQuery.Append("UPDATE articles SET published='1', moderator_userid='")
         .Append(Utils.Escape(HttpContext.Current.User.Identity.Name)).Append("' WHERE articleid='")
         .Append(Utils.Escape(article["articleid"])).Append("'; UPDATE articles_thread SET articleid_current='")
         .Append(Utils.Escape(article["articleid"])).Append("' WHERE threadid='")
         .Append(Utils.Escape(article["threadid"])).Append("';")
         .Append(insertEvent(RecentChanges_EventType.Published, HttpContext.Current.User.Identity.Name, article["articleid"], article["threadid"]));
         conn.Query_Execute(publishQuery.ToString());
         conn.Disconnect();
         response.Redirect(pageElements["URL"] + "/article/" + article["articleid"]);
     }
     content.Append(
         Core.templates["articles"]["article_publish"]
         );
 }
예제 #36
0
 public static void pageDownload_ResetDownloads(string pluginid, Connector conn, ref Misc.PageElements pageElements, HttpRequest request, HttpResponse response, bool admin, ResultRow file)
 {
     if (request.Form["confirm"] != null)
     {
         conn.Query_Execute("DELETE FROM downloads WHERE downloadid='" + Utils.Escape(file["downloadid"]) + "'");
         conn.Disconnect();
         response.Redirect(pageElements["URL"] + "/download/" + file["downloadid"]);
     }
     pageElements["CONTENT"] = Core.templates["downloads"]["download_reset"]
         .Replace("%DOWNLOADID%", file["downloadid"]);
     pageElements["TITLE"] = "Download - " + HttpUtility.HtmlEncode(file["title"]) + " - Reset Downloads";
 }
예제 #37
0
 public ResultRowChangeEvent(ResultRow row, global::System.Data.DataRowAction action) {
     this.eventRow = row;
     this.eventAction = action;
 }
예제 #38
0
        public static void pageArticle_View_Delete(ref string pluginid, ref Connector conn, ref Misc.PageElements pageElements, ref HttpRequest request, ref HttpResponse response, ref bool permCreate, ref bool permDelete, ref bool permPublish, ref bool owner, ref StringBuilder content, ref ResultRow article)
        {
            string error = null;
            string captcha = request.Form["captcha"];

            if (request.Form["confirm"] != null && captcha != null)
            {
                if (!Common.Validation.validCaptcha(captcha))
                    error = "Incorrect captcha verification code!";
                else
                {
                    // Delete the article
                    conn.Query_Execute("DELETE FROM articles WHERE articleid='" + Utils.Escape(article["articleid"]) + "';" + insertEvent(RecentChanges_EventType.Deleted, HttpContext.Current.User.Identity.Name, article["articleid"], article["threadid"]));
                    // Check if any more articles exist and if a current article is set
                    ResultRow thread = conn.Query_Read("SELECT (SELECT articleid_current FROM articles_thread WHERE threadid='" + Utils.Escape(article["threadid"]) + "') AS current_article, (SELECT COUNT('') FROM articles WHERE threadid='" + Utils.Escape(article["threadid"]) + "') AS articles_remaining")[0];
                    StringBuilder finalQuery = new StringBuilder();
                    if (thread["current_article"].Length == 0)
                    {
                        // Set a new article
                        if (int.Parse(thread["articles_remaining"]) == 0)
                            // Delete the thread
                            finalQuery.Append("DELETE FROM articles_thread WHERE threadid='" + Utils.Escape(article["threadid"]) + "';");
                        else
                            // Set a new article
                            finalQuery.Append("UPDATE articles_thread SET articleid_current=(SELECT articleid FROM articles WHERE published='1' AND threadid='" + Utils.Escape(article["threadid"]) + "' ORDER BY articleid DESC LIMIT 1) WHERE threadid='" + Utils.Escape(article["threadid"]) + "';");
                    }
                    // Append tags cleanup query
                    finalQuery.Append(QUERY_TAGS_CLEANUP);
                    // Finish up
                    conn.Query_Execute(finalQuery.ToString());
                    conn.Disconnect();
                    response.Redirect(pageElements["URL"] + "/articles", true);
                }
            }
            // Display form
            if (error != null)
                content.Append(
                    Core.templates[pageElements["TEMPLATE"]]["error"].Replace("<ERROR>", HttpUtility.HtmlEncode(error))
                    );
            content.Append(
                Core.templates["articles"]["article_delete"]
            );
        }
		protected virtual bool LoadFromDatabase(ResultRow row) {
			if (CacheProperties() == false) {
				return false;
			}

			var dict = mDatabaseProperties[GetType()];
			foreach (KeyValuePair<PropertyInfo, StoreableDatabaseObjectAttribute> kvp in dict) {
				StoreableDatabaseObjectAttribute att = kvp.Value;
				PropertyInfo prop = kvp.Key;
				string dbName = att.DatabaseName;


				if (row.Table.Columns.Contains(dbName) == false) {
					ServerConsole.ErrorLine("Column '{0}' not found in table!", dbName);
					continue;
				}

				object value = row[dbName].Value;
				Type valueType = value.GetType();
				// Catch value "null"
				if (value is DBNull) {
					value = null;
				}
				// Enum's need the exact Enum value..
				if (prop.PropertyType.IsEnum == true) {
					Type enumType = prop.PropertyType;
					value = Enum.ToObject(enumType, (value == null ? 0 : value));
				}

				prop.SetValue(this, value, null);
			}

			return true;
		}
예제 #40
0
 private Table<ResultRow> Select_6ea90561ec26483685c68cc37a476cfa()
 {
     Call(3);
     RuntimeTable<ResultRow> result = new RuntimeTable<ResultRow>();
     result.AddColumn("url");
     result.AddColumn("(No column name)");
     CodeTable<anon_e77da3131e1d4cf1970c18c99c04c921> fromTable = From_063aa67f80e6401686b3f3c73c24dfc4();
     fromTable = Where_18735c6e301a42d68fee5c66fc258c09(fromTable);
     IEnumerator<anon_e77da3131e1d4cf1970c18c99c04c921> x = fromTable.GetEnumerator();
     for (
     ; x.MoveNext();
     )
     {
         anon_e77da3131e1d4cf1970c18c99c04c921 row = x.Current;
         IEnumerator<HtmlNode> y = row.DownloadPage.nodes.GetEnumerator();
         for (
         ; y.MoveNext();
         )
         {
             HtmlNode node = y.Current;
             ResultRow resultRow = new ResultRow(2);
             resultRow[0] = row.DownloadPage.url;
             resultRow[1] = string.Concat("http://www.target.com", node.Pick("a:first-child").TakeAttribute("href"));
             if (((resultRow[0] != null)
                         && (resultRow[1] != null)))
             {
                 result.Add(resultRow);
             }
         }
         row.DownloadPage.Clear();
     }
     OnSelect(result);
     return result;
 }
예제 #41
0
 public static void pageDownload_Delete(string pluginid, Connector conn, ref Misc.PageElements pageElements, HttpRequest request, HttpResponse response, bool admin, ResultRow file)
 {
     if (!admin) return;
     if (request.Form["confirm"] != null)
     {
         // Delete file
         File.Delete(downloadsPath.Replace("\\", "/") + "/" + file["physical_path"]);
         // Delete from database
         conn.Query_Execute("DELETE FROM downloads_files WHERE downloadid='" + Utils.Escape(file["downloadid"]) + "';" + QUERY_ICONCACHE_CLEANUP);
         // End response
         conn.Disconnect();
         response.Redirect(pageElements["URL"] + "/downloads/" + (file["physical_path"].LastIndexOf('/') != -1 ? file["physical_path"].Substring(0, file["physical_path"].LastIndexOf('/')) : string.Empty));
     }
     pageElements["CONTENT"] = Core.templates["downloads"]["download_delete"]
         .Replace("%DOWNLOADID%", file["downloadid"])
         .Replace("%PHYSICAL_PATH%", HttpUtility.HtmlEncode(downloadsPath.Replace("\\", "/") + "/" + file["physical_path"]))
         .Replace("%PATH%", HttpUtility.HtmlEncode(file["physical_path"]))
         ;
     pageElements["TITLE"] = "Download - " + HttpUtility.HtmlEncode(file["title"]) + " - Confirm Deletion";
 }
예제 #42
0
 public static void pageDownload_Edit(string pluginid, Connector conn, ref Misc.PageElements pageElements, HttpRequest request, HttpResponse response, bool admin, ResultRow file)
 {
     if (!admin) return;
     string error = null;
     string title = request.Form["title"];
     string description = request.Form["description"];
     if (title != null && description != null)
     {
         try
         {
             if (title.Contains("*") || title.Contains("%") || title.Contains("|") || title.Contains("\\") || title.Contains("/") || title.Contains(":") || title.Contains("\"") || title.Contains("<") || title.Contains(">") || title.Contains("?"))
                 error = "Title has invalid character(s) - the following are disallowed: * | \\ / : \" < > ? %";
             else
             {
                 if (title != file["title"])
                 {
                     // Move the file to rename it
                     File.Move(downloadsPath.Replace("\\", "/") + "/" + file["physical_path"], downloadsPath.Replace("\\", "/") + "/" + file["physical_path"].Substring(0, file["physical_path"].Length - file["title"].Length) + title);
                 }
                 conn.Query_Execute("UPDATE downloads_files SET title='" + Utils.Escape(title) + "', description='" + Utils.Escape(description) + "' WHERE downloadid='" + Utils.Escape(file["downloadid"]) + "'");
                 conn.Disconnect();
                 response.Redirect(pageElements["URL"] + "/download/" + file["downloadid"]);
             }
         }
         catch (Exception ex)
         {
             error = "Failed to update file - " + ex.Message + " (" + ex.GetBaseException().Message + ") - " + ex.StackTrace + "!";
         }
     }
     pageElements["CONTENT"] = Core.templates["downloads"]["download_edit"]
         .Replace("%DOWNLOADID%", file["downloadid"])
         .Replace("%ERROR%", error != null ? Core.templates[pageElements["TEMPLATE"]]["error"].Replace("<ERROR>", HttpUtility.HtmlEncode(error)) : string.Empty)
         .Replace("%TITLE%", HttpUtility.HtmlEncode(title ?? file["title"]))
         .Replace("%DESCRIPTION%", HttpUtility.HtmlEncode(description ?? file["description"]));
     pageElements["TITLE"] = "Download - " + HttpUtility.HtmlEncode(file["title"]) + " - Edit Description";
 }
예제 #43
0
 public static void pageDownload_Get(string pluginid, Connector conn, ref Misc.PageElements pageElements, HttpRequest request, HttpResponse response, bool admin, ResultRow file)
 {
     // This download method borrows code from Uber Media; much credit to http://forums.asp.net/t/1218116.aspx
     string path = downloadsPath + "/" + file["physical_path"];
     if (!File.Exists(path))
     {
         conn.Disconnect();
         response.StatusCode = 500;
         response.Write("Failed to physically locate the file, please try your request again or contact us immediately!");
         response.End();
     }
     try
     {
         // Clear the response so far, as well as disable the buffer
         response.Clear();
         response.Buffer = false;
         // Based on RFC 2046 - page 4 - media types - point 5 - http://www.rfc-editor.org/rfc/rfc2046.txt - http://stackoverflow.com/questions/1176022/unknown-file-type-mime
         response.ContentType = "application/octet-stream";
         FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
         BinaryReader bin = new BinaryReader(fs);
         long startRead = 0;
         // Read the range of bytes requested - allows downloads to be continued
         if (request.Headers["Range"] != null)
         {
             string[] range = request.Headers["Range"].Split(new char[] { '=', '-' }); // RFC 2616 - section 14.35
             // Ensure there are at least two parts
             if (range.Length >= 2)
             {
                 // Attempt to parse the requested bytes
                 long.TryParse(range[1], out startRead);
                 // Ensure its inclusive of 0 to size of file, else reset it to zero
                 if (startRead < 0 || startRead >= fs.Length) startRead = 0;
                 else
                     // Write the range of bytes being sent - RFC 2616 - section 14.16
                     response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startRead, fs.Length - 1, fs.Length));
             }
         }
         // Specify the number of bytes being sent
         response.AddHeader("Content-Length", (fs.Length - startRead).ToString());
         // Specify other headers
         string lastModified = file["datetime"];
         response.AddHeader("Connection", "Keep-Alive");
         response.AddHeader("Last-Modified", lastModified);
         response.AddHeader("ETag", HttpUtility.UrlEncode(file["physical_path"], System.Text.Encoding.UTF8) + lastModified); // Unique entity identifier
         response.AddHeader("Accept-Ranges", "bytes");
         response.AddHeader("Content-Disposition", "attachment;filename=" + file["title"]);
         response.StatusCode = 206;
         // Start the stream at the offset
         bin.BaseStream.Seek(startRead, SeekOrigin.Begin);
         const int chunkSize = 16384; // 16kb will be transferred at a time
         // Write bytes whilst the user is connected in chunks of 1024 bytes
         int maxChunks = (int)Math.Ceiling((double)(fs.Length - startRead) / chunkSize);
         int i;
         for (i = 0; i < maxChunks && response.IsClientConnected; i++)
         {
             response.BinaryWrite(bin.ReadBytes(chunkSize));
             response.Flush();
         }
         if (i >= maxChunks)
         {
             // Download was successful - log it
             conn.Query_Execute("INSERT INTO downloads (downloadid, ip_addr, datetime) VALUES('" + Utils.Escape(file["downloadid"]) + "', '" + Utils.Escape(request.UserHostAddress) + "', NOW());");
         }
         bin.Close();
         fs.Close();
     }
     catch
     {
         response.StatusCode = 500;
         response.Write("Failed to get file, please try your request again or contact us immediately!");
     }
     conn.Disconnect();
     response.End();
 }
예제 #44
0
 private ResultRow GetResultRow(IEnumerable<RowData> rowDatas, bool byProtein)
 {
     ResultRow resultRow = null;
     var rowDatasByCohort = new Dictionary<CohortKey, IList<RowData>>();
     foreach (var rowData in rowDatas)
     {
         if (resultRow == null)
         {
             var peptide = Workspace.Peptides.GetChild(rowData.PeptideId);
             resultRow = new ResultRow
                             {
                                 PeptideSequence = byProtein ? null : peptide.FullSequence,
                                 ProteinDescription = peptide.ProteinDescription,
                                 ProteinName = peptide.ProteinName,
                                 ProteinKey = peptide.GetProteinKey(),
                             };
         }
         IList<RowData> list;
         if (!rowDatasByCohort.TryGetValue(rowData.CohortKey, out list))
         {
             list = new List<RowData>();
             rowDatasByCohort.Add(rowData.CohortKey, list);
         }
         list.Add(rowData);
     }
     foreach (var entry in rowDatasByCohort)
     {
         resultRow.ResultDatas.Add(entry.Key, GetResultData(entry.Value));
     }
     return resultRow;
 }
예제 #45
0
        public static void pageDownload_Thumb(string pluginid, Connector conn, ref Misc.PageElements pageElements, HttpRequest request, HttpResponse response, bool admin, ResultRow file)
        {
            // Check the background has been loaded/cached
            if (pageDownload_Thumb_bbcode == null)
                pageDownload_Thumb_bbcode = (Bitmap)Image.FromFile(Core.basePath + "\\Content\\Images\\downloads\\bbcode.png");
            // Construct the image
            Bitmap output = (Bitmap)pageDownload_Thumb_bbcode.Clone();
            Graphics g = Graphics.FromImage(output);
            // Grab the associated icon
            byte[] rawIcon = null;
            if (file["iconid"].Length > 0 && file["iconid"] != "0")
            {
                // Grab the icon generated of the file
                Result data = conn.Query_Read("SELECT data FROM downloads_files_icons WHERE iconid='" + Utils.Escape(file["iconid"]) + "'");
                if (data.Rows.Count == 1)
                    rawIcon = data[0].GetByteArray("data");
            }
            if (rawIcon == null && file["extension"].Length > 0)
            {
                // Grab the icon associated with the extension
                Result data = conn.Query_Read("SELECT icon FROM downloads_ext_icons WHERE extension='" + Utils.Escape(file["extension"]) + "'");
                if (data.Rows.Count == 1)
                    rawIcon = data[0].GetByteArray("icon");
            }
            if (rawIcon == null)
            {
                // Associate unknown extension with this file
                if (pageDownloads_Icon_Unknown == null)
                    loadUknownIcon();
                rawIcon = pageDownloads_Icon_Unknown;
            }
            // Draw icon
            MemoryStream ms = new MemoryStream(rawIcon);
            Bitmap icon = (Bitmap)Image.FromStream(ms);
            // Apply fake rounded edges
            icon.SetPixel(0, 0, Color.Transparent); // Top-left
            icon.SetPixel(1, 0, Color.Transparent);
            icon.SetPixel(0, 1, Color.Transparent);

            icon.SetPixel(31, 0, Color.Transparent); // Top-right
            icon.SetPixel(30, 0, Color.Transparent);
            icon.SetPixel(31, 1, Color.Transparent);

            icon.SetPixel(0, 31, Color.Transparent); // Bottom-left
            icon.SetPixel(0, 30, Color.Transparent);
            icon.SetPixel(1, 31, Color.Transparent);

            icon.SetPixel(31, 31, Color.Transparent); // Bottom-right
            icon.SetPixel(31, 30, Color.Transparent);
            icon.SetPixel(30, 31, Color.Transparent);
            g.DrawImage(icon, 5, 8, 32, 32);
            icon.Dispose();
            ms.Dispose();
            // Draw title
            g.DrawString(file["title"], new Font("Arial", 12.0f, FontStyle.Regular, GraphicsUnit.Pixel), new SolidBrush(Color.White), 40, 8);
            // Draw downloads
            g.DrawString(conn.Query_Scalar("SELECT COUNT('') FROM (SELECT ip_addr FROM downloads WHERE downloadid='" + Utils.Escape(file["downloadid"]) + "' GROUP BY ip_addr) AS a").ToString() + " downloads", new Font("Arial", 12.0f, FontStyle.Regular, GraphicsUnit.Pixel), new SolidBrush(Color.LightGray), 40, 24);
            // Output it to the user
            ms = new MemoryStream();
            output.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
            output.Dispose();
            response.ContentType = "image/png";
            response.BinaryWrite(ms.ToArray());
            ms.Dispose();
            conn.Disconnect();
            response.End();
        }
예제 #46
0
 public static void pageDownload_View(string pluginid, Connector conn, ref Misc.PageElements pageElements, HttpRequest request, HttpResponse response, bool admin, ResultRow file)
 {
     // Get downloads
     ResultRow downloads = conn.Query_Read("SELECT (SELECT COUNT('') FROM downloads WHERE downloadid='" + Utils.Escape(file["downloadid"]) + "') AS downloads_total, (SELECT COUNT('') FROM (SELECT ip_addr FROM downloads WHERE downloadid='" + Utils.Escape(file["downloadid"]) + "' GROUP BY ip_addr) AS a) AS downloads_unique")[0];
     // Render page
     pageElements["CONTENT"] = Core.templates["downloads"]["download_get"]
         .Replace("%DOWNLOADID%", file["downloadid"])
         .Replace("%NAV%", getNavBar(file["physical_path"].LastIndexOf('/') == -1 ? string.Empty : file["physical_path"].Substring(0, file["physical_path"].LastIndexOf('/'))))
         .Replace("%EXTENSION%", HttpUtility.HtmlEncode(file["extension"]))
         .Replace("%FILESIZE%", HttpUtility.HtmlEncode(file["file_size"].Length > 0 ? Misc.Plugins.getBytesString(float.Parse(file["file_size"])) : "unknown bytes"))
         .Replace("%DESCRIPTION%", file["description"].Length > 0 ? HttpUtility.HtmlEncode(file["description"]) : "(no description)")
         .Replace("%ICONID%", HttpUtility.HtmlEncode(file["iconid"]))
         .Replace("%DOWNLOADS_TOTAL%", downloads["downloads_total"])
         .Replace("%DOWNLOADS_UNIQUE%", downloads["downloads_unique"])
         .Replace("%DIRECT_LINK%", "http://" + request.Url.Host + (request.Url.Port != 80 ? ":" + request.Url.Port : string.Empty) + "/download/" + file["downloadid"] + "." + file["extension"])
         ;
     pageElements["TITLE"] = "Download - " + HttpUtility.HtmlEncode(file["title"]);
     // Admin flag
     if (admin) pageElements.setFlag("DOWNLOADS_ADMIN");
     // Add CSS
     Misc.Plugins.addHeaderCSS(pageElements["URL"] + "/Content/CSS/Downloads.css", ref pageElements);
 }
예제 #47
0
 public static void pageArticle_View_History(ref string pluginid, ref Connector conn, ref Misc.PageElements pageElements, ref HttpRequest request, ref HttpResponse response, ref bool permCreate, ref bool permDelete, ref bool permPublish, ref bool owner, ref StringBuilder content, ref ResultRow article)
 {
     // Setup the page being viewed
     int page;
     string rawPage = request.QueryString["apg"];
     if (rawPage == null || !int.TryParse(rawPage, out page) || page < 1) page = 1;
     // Append header
     content.Append(
         Core.templates["articles"]["history_header"]
         );
     // Grab the current selected article
     string currentArticleID = (conn.Query_Scalar("SELECT articleid_current FROM articles_thread WHERE threadid='" + Utils.Escape(article["threadid"]) + "'") ?? string.Empty).ToString();
     // Append each article revision
     int historyPerPage = Core.settings[SETTINGS_KEY].getInt(SETTINGS_HISTORY_PER_PAGE);
     Result articles = conn.Query_Read("SELECT a.*, u.username, u2.username AS author FROM articles AS a LEFT OUTER JOIN bsa_users AS u ON u.userid=a.moderator_userid LEFT OUTER JOIN bsa_users AS u2 ON u2.userid=a.userid WHERE a.threadid='" + Utils.Escape(article["threadid"]) + "' ORDER BY a.articleid DESC LIMIT " + ((historyPerPage * page) - historyPerPage) + "," + historyPerPage);
     foreach (ResultRow a in articles)
     {
         content.Append(
             Core.templates["articles"]["history_row"]
             .Replace("<ARTICLEID>", HttpUtility.HtmlEncode(a["articleid"]))
             .Replace("<SELECTED>", a["articleid"] == currentArticleID ? "SELECTED" : string.Empty)
             .Replace("<TITLE>", HttpUtility.HtmlEncode(a["title"]))
             .Replace("<PUBLISHED>", a["published"].Equals("1") ? "Published by " + HttpUtility.HtmlEncode(a["username"]) : "Pending publication.")
             .Replace("<DATETIME>", a["datetime"].Length > 0 ? a["datetime"] : "Unknown")
             .Replace("<DATETIME_SHORT>", a["datetime"].Length > 0 ? Misc.Plugins.getTimeString(DateTime.Parse(a["datetime"])) : "Unknown")
             .Replace("<CREATOR_USERID>", HttpUtility.HtmlEncode(a["userid"]))
             .Replace("<CREATOR>", HttpUtility.HtmlEncode(a["author"]))
             );
     }
     // Append navigator
     content.Append(
         Core.templates["articles"]["page_nav"]
         .Replace("<SUBPAGE>", "history")
         .Replace("<PAGE>", page.ToString())
         .Replace("<PAGE_PREVIOUS>", (page > 1 ? page - 1 : 1).ToString())
         .Replace("<PAGE_NEXT>", (page < int.MaxValue ? page + 1 : int.MaxValue).ToString())
         );
     // Set navigator flags
     if (page > 1)
         pageElements.setFlag("ARTICLE_PAGE_PREVIOUS");
     if (page < int.MaxValue && articles.Rows.Count == historyPerPage)
         pageElements.setFlag("ARTICLE_PAGE_NEXT");
 }
예제 #48
0
        /// <summary>
        /// <paramref name="reader"/>를 읽어, <see cref="ResultRow"/>의 컬렉션인 <see cref="ResultSet"/>을 빌드합니다.
        /// </summary>
        /// <param name="reader">DataReader</param>
        /// <param name="nameMapper">컬럼명을 속성명으로 매핑해주는 매퍼입니다.</param>
        /// <param name="firstResult">첫번째 레코드 인덱스 (0부터 시작)</param>
        /// <param name="maxResults">최대 레코드 수</param>
        /// <returns><see cref="ResultSet"/> 인스턴스</returns>
        public static ResultSet CreateResultSet(this IDataReader reader, INameMapper nameMapper, int firstResult, int maxResults) {
            reader.ShouldNotBeNull("reader");

            if(nameMapper == null)
                nameMapper = new SameNameMapper();

            if(IsDebugEnabled)
                log.Debug("IDataReader로부터 정보를 읽어 ResultRow들을 만들어 ResultSet 으로 빌드합니다...");

            var resultSet = new ResultSet();

            while(firstResult-- > 0) {
                if(reader.Read() == false)
                    return resultSet;
            }

            if(maxResults <= 0)
                maxResults = int.MaxValue;

            resultSet.FieldNames = reader.GetFieldNames();

            var rowIndex = 0;
            while(reader.Read() && rowIndex++ < maxResults) {
                var row = new ResultRow();

                foreach(var fieldName in resultSet.FieldNames)
                    row.Add(nameMapper.MapToPropertyName(fieldName), reader.AsValue(fieldName));

                resultSet.Add(row);
            }

            if(IsDebugEnabled)
                log.Debug("IDataReader로부터 정보를 읽어 ResultSet을 빌드했습니다!!! Row Count=[{0}]", resultSet.Count);

            return resultSet;
        }
예제 #49
0
        public void ShowRow(ResultRow row)
        {
            if (row.Table.HasEntities)
            {
                Lite<Entity> lite = row.Entity;

                if (Navigator.IsNavigable(lite.EntityType, isSearch: true))
                    Navigator.NavigateUntyped(lite);
            }
            else
            {
                var subFilters = lastRequest.GetFilter(row);

                Finder.Explore(new ExploreOptions(Request.QueryName)
                {
                    FilterOptions = lastRequest.Filters.Concat(subFilters).ToList(),
                    SearchOnLoad = true,
                });
            }
        }
예제 #50
0
 public void RemoveResultRow(ResultRow row) {
     this.Rows.Remove(row);
 }
		public StoreableDatabaseObject(ResultRow row) {
			if (row != null) {
				LoadFromDatabase(row);
			}
		}
예제 #52
0
 public static void pageProfile_Upload(string pluginid, ref ResultRow profileData, Connector conn, ref Misc.PageElements pageElements, HttpRequest request, HttpResponse response)
 {
     string error = null;
     HttpPostedFile image = request.Files["profile_picture"];
     if(image != null)
     {
         int maxSize = Core.settings[SETTINGS_KEY].getInt(SETTINGS_KEY_PICTURE_MAX_SIZE);
         if (image.ContentLength > maxSize)
             error = "Picture cannot exceed " + maxSize + " bytes (" + Misc.Plugins.getBytesString(maxSize) + ") !";
         else if (image.ContentType != "image/gif" && image.ContentType != "image/jpeg" && image.ContentType != "image/png" && image.ContentType != "image/jpg")
             error = "Invalid file format!";
         else
         {
             // Compress the image
             double maxWidth = Core.settings[SETTINGS_KEY].getDouble(SETTINGS_KEY_PICTURE_MAX_WIDTH);
             double maxHeight = Core.settings[SETTINGS_KEY].getDouble(SETTINGS_KEY_PICTURE_MAX_HEIGHT);
             Stream bStream = image.InputStream;
             Image pp = Image.FromStream(bStream);
             // Work-out the size of the new image
             int width;
             int height;
             if (pp.Width > maxWidth)
             {
                 width = (int)maxWidth;
                 height = (int)((maxWidth / (double)pp.Width) * pp.Height);
             }
             else
             {
                 height = (int)maxHeight;
                 width = (int)((maxHeight / (double)pp.Height) * pp.Width);
             }
             Bitmap compressedImage = new Bitmap(width, height);
             // Draw the uploaded image
             Graphics g = Graphics.FromImage(compressedImage);
             g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
             g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
             g.DrawImage(pp, 0, 0, width, height);
             g.Dispose();
             // Save the image as a byte-array
             MemoryStream ms = new MemoryStream();
             compressedImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
             byte[] data = ms.ToArray();
             ms.Dispose();
             ms = null;
             // Dispose image
             compressedImage.Dispose();
             compressedImage = null;
             pp.Dispose();
             pp = null;
             bStream.Dispose();
             bStream = null;
             // Save the byte-array to the database
             Dictionary<string, object> queryParams = new Dictionary<string, object>();
             queryParams.Add("profile_picture", data);
             queryParams.Add("profileid", profileData["profileid"]);
             // Save the byte-array to the database
             conn.Query_Execute_Parameters("UPDATE bsa_profiles SET profile_picture=@profile_picture WHERE profileid=@profileid", queryParams);
             // Redirect to profile
             conn.Disconnect();
             response.Redirect(pageElements["URL"] + "/profile?userid=" + profileData["userid"], true);
         }
     }
     pageElements["PROFILE_CONTENT"] = Core.templates["bsa_profiles"]["profile_upload"]
         .Replace("<USERID>", HttpUtility.HtmlEncode(profileData["userid"]))
         .Replace("<ERROR>", error != null ? Core.templates[pageElements["TEMPLATE"]]["error"].Replace("<ERROR>", HttpUtility.HtmlEncode(error)) : string.Empty);
     pageElements.setFlag("PROFILE_UPLOAD");
 }
예제 #53
0
        /// <summary>
        /// 요청 쿼리 문을 수행하는데, 
        /// <see cref="IAdoRepository.ExecuteNonQuery(string,IAdoParameter[])" /> 나 
        /// <see cref="IAdoRepository.ExecuteScalar(string,IAdoParameter[])"/> 를 실행합니다.
        /// </summary>
        /// <param name="requestItem"></param>
        /// <param name="responseItem"></param>
        /// <param name="adoParameters"></param>
        protected virtual void ExecuteQuery(RequestItem requestItem, ResponseItem responseItem, IAdoParameter[] adoParameters) {
            // Scalar 값 구하기
            if(requestItem.ResponseFormat == ResponseFormatKind.Scalar) {
                if(IsDebugEnabled)
                    log.Debug("ExecuteNonScalar 를 수행하여, ResultValue 값을 설정합니다...");

                responseItem.ResultValue = AdoRepository.ExecuteScalar(requestItem.Query, adoParameters);
                return;
            }

            // 쿼리문이라면, 실행
            var query = requestItem.Query;
            if(AdoTool.IsSqlString(query)) {
                if(IsDebugEnabled)
                    log.Debug("ExecuteNonQuery 를 수행하고, 영향받은 행의 수를 ResultValue에 설정합니다...");

                responseItem.ResultValue = AdoRepository.ExecuteNonQuery(requestItem.Query, adoParameters);
                return;
            }


            if(IsDebugEnabled)
                log.Debug("ExecuteProcedure를 수행하고, Parameter 정보들을 ResultSet에 설정합니다.");

            //  Procedure 라면, Output Parameter 등을 ResultSet으로 반환함.
            //! 단 Procedure가 ResultSet을 반환해야 하는 경우는 OpenQuery를 수행할 수 있도록 ResponseFormat 을 ResponseFormatKind.ResultSet 으로 할 것
            //
            var parameters = AdoRepository.ExecuteProcedure(query, adoParameters);

            if(parameters != null) {
                responseItem.ResultValue = parameters.GetReturnValue();

                var row = new ResultRow(parameters.ToDictionary(p => p.Name, p => p.Value));
                responseItem.ResultSet.Add(row);
            }
        }
예제 #54
0
 public static void pageArticle_View_Rebuild(ref string pluginid, ref Connector conn, ref Misc.PageElements pageElements, ref HttpRequest request, ref HttpResponse response, ref bool permCreate, ref bool permDelete, ref bool permPublish, ref bool owner, ref StringBuilder content, ref ResultRow article)
 {
     if (!permPublish) return;
     StringBuilder cached = new StringBuilder(article["body"]);
     // Rebuild article text
     articleViewRebuildCache(conn, ref cached, article["allow_html"].Equals("1"), ref pageElements);
     conn.Query_Execute("UPDATE articles SET body_cached='" + Utils.Escape(cached.ToString()) + "' WHERE articleid='" + Utils.Escape(article["articleid"]) + "';" + insertEvent(RecentChanges_EventType.RebuiltArticleCache, HttpContext.Current.User.Identity.Name, article["articleid"], article["threadid"]));
     conn.Disconnect();
     // Rebuild article pdf if this is the current article
     string currentArticleID = (conn.Query_Scalar("SELECT articleid_current FROM articles_thread WHERE threadid='" + Utils.Escape(article["threadid"]) + "'") ?? string.Empty).ToString();
     if(currentArticleID == article["articleid"])
         pdfRebuild(pluginid, article["articleid"], article["title"], article["pdf_name"], article["threadid"], request);
     // Redirect back to the article
     response.Redirect(pageElements["URL"] + "/article/" + article["articleid"], true);
 }
예제 #55
0
 public static void pageArticle_View_Set(ref string pluginid, ref Connector conn, ref Misc.PageElements pageElements, ref HttpRequest request, ref HttpResponse response, ref bool permCreate, ref bool permDelete, ref bool permPublish, ref bool owner, ref StringBuilder content, ref ResultRow article)
 {
     conn.Query_Execute("UPDATE articles_thread SET articleid_current='" + Utils.Escape(article["articleid"]) + "' WHERE threadid='" + Utils.Escape(article["threadid"]) + "';" + insertEvent(RecentChanges_EventType.SetAsSelected, HttpContext.Current.User.Identity.Name, article["articleid"], article["threadid"]));
     conn.Disconnect();
     response.Redirect(pageElements["URL"] + "/article/" + article["articleid"], true);
 }
예제 #56
0
 public static void pageDownload_Move(string pluginid, Connector conn, ref Misc.PageElements pageElements, HttpRequest request, HttpResponse response, bool admin, ResultRow file)
 {
     if (!admin) return;
     string error = null;
     string folderid = request.Form["folderid"];
     if (folderid != null)
     {
         // Validate the new folder
         if (folderid.Length == 0)
             error = "Invalid folder!";
         else if (folderid == file["folderid"])
             error = "The newly selected Folder is the same as the current folder!";
         else
         {
             // Grab the folder's details to validate it exists
             Result ff = conn.Query_Read("SELECT folderid, path, title FROM downloads_folders WHERE folderid='" + Utils.Escape(folderid) + "'");
             if (ff.Rows.Count != 1)
                 error = "Folder does not exist!";
             else
             {
                 // Attempt to move the file, else we'll roll-back our actions and inform the user
                 try
                 {
                     string dest = ff[0]["path"] + (ff[0]["path"].Length > 0 ? "/" : string.Empty) + ff[0]["title"] + "/" + file["title"]; // Destination path of the file, including the filename
                     File.Move(downloadsPath.Replace("\\", "/") + "/" + file["physical_path"], downloadsPath.Replace("\\", "/") + "/" + dest);
                     conn.Query_Execute("UPDATE downloads_files SET folderid='" + Utils.Escape(ff[0]["folderid"]) + "', physical_path='" + Utils.Escape(dest) + "' WHERE downloadid='" + Utils.Escape(file["downloadid"]) + "'");
                     conn.Disconnect();
                     response.Redirect(pageElements["URL"] + "/download/" + file["downloadid"]);
                 }
                 catch(Exception ex)
                 {
                     error = "Failed to move file - " + ex.Message + " (" + ex.GetBaseException().Message + ") - " + ex.StackTrace + "!";
                 }
             }
         }
     }
     StringBuilder folders = new StringBuilder();
     foreach (ResultRow folder in conn.Query_Read("SELECT folderid, CONCAT(CONCAT(path, '/'), title) AS path FROM downloads_folders ORDER BY path ASC"))
         if(folder["folderid"] != file["folderid"])
             folders.Append("<option value=\"").Append(folder["folderid"]).Append("\">").Append(HttpUtility.HtmlEncode(folder["path"])).Append("</option>");
     // Render page
     pageElements["CONTENT"] = Core.templates["downloads"]["download_move"]
         .Replace("%ERROR%", error != null ? Core.templates[pageElements["TEMPLATE"]]["error"].Replace("<ERROR>", HttpUtility.HtmlEncode(error)) : string.Empty)
         .Replace("%DOWNLOADID%", file["downloadid"])
         .Replace("%FOLDERS%", folders.ToString());
     pageElements["TITLE"] = "Download - " + HttpUtility.HtmlEncode(file["title"]) + " - Move";
 }
예제 #57
0
        /// <summary>
        /// <paramref name="reader"/>를 읽어, <see cref="ResultRow"/>를 빌드합니다.
        /// </summary>
        /// <param name="reader">DataReader</param>
        /// <param name="fieldNames">컬럼명 리스트</param>
        /// <param name="nameMapper">컬럼명을 속성명으로 매핑해주는 매퍼입니다.</param>
        /// <returns></returns>
        internal static ResultRow CreateResultRow(this IDataReader reader, IList<string> fieldNames, INameMapper nameMapper) {
            Guard.Assert(reader.IsClosed == false, "reader 가 닫혀있습니다.");

            var row = new ResultRow();

            foreach(var fieldName in fieldNames)
                row.Add(nameMapper.MapToPropertyName(fieldName), reader.AsValue(fieldName));

            return row;
        }
예제 #58
0
 public static void pageProfile_About(string pluginid, ref ResultRow profileData, Connector conn, ref Misc.PageElements pageElements, HttpRequest request, HttpResponse response)
 {
     // Build contact details
     StringBuilder contact = new StringBuilder();
     // -- Github
     if (profileData["contact_github"].Length > 0)
         contact.Append(Core.templates["bsa_profiles"]["profile_about_contact"]
             .Replace("<URL>", "https://github.com/" + HttpUtility.HtmlEncode(profileData["contact_github"]))
             .Replace("<IMAGE>", "https://github.com/favicon.ico")
             .Replace("<TITLE>", HttpUtility.HtmlEncode(profileData["contact_github"])));
     // -- Website
     if (profileData["contact_website"].Length > 0)
         contact.Append(Core.templates["bsa_profiles"]["profile_about_contact"]
             .Replace("<URL>", "http://" + HttpUtility.HtmlEncode(profileData["contact_website"]))
             .Replace("<IMAGE>", pageElements["ADMIN_URL"] + "/Content/Images/bsa_profiles/website.png")
             .Replace("<TITLE>", HttpUtility.HtmlEncode(profileData["contact_website"])));
     // -- Email
     if (profileData["contact_email"].Length > 0)
         contact.Append(Core.templates["bsa_profiles"]["profile_about_contact"]
             .Replace("<URL>", "mailto:" + HttpUtility.HtmlEncode(profileData["contact_email"]))
             .Replace("<IMAGE>", pageElements["ADMIN_URL"] + "/Content/Images/bsa_profiles/website.png")
             .Replace("<TITLE>", HttpUtility.HtmlEncode(profileData["contact_email"])));
     // -- Facebook
     if(profileData["contact_facebook"].Length > 0)
         contact.Append(Core.templates["bsa_profiles"]["profile_about_contact"]
             .Replace("<URL>", "http://www.facebook.com/" + HttpUtility.HtmlEncode(profileData["contact_facebook"]))
             .Replace("<IMAGE>", "http://facebook.com/favicon.ico")
             .Replace("<TITLE>", HttpUtility.HtmlEncode(profileData["contact_facebook"])));
     // -- G+
     if (profileData["contact_googleplus"].Length > 0)
         contact.Append(Core.templates["bsa_profiles"]["profile_about_contact"]
             .Replace("<URL>", "https://plus.google.com/" + HttpUtility.HtmlEncode(profileData["contact_googleplus"]))
             .Replace("<IMAGE>", "http://plus.google.com/favicon.ico")
             .Replace("<TITLE>", HttpUtility.HtmlEncode(profileData["contact_googleplus"])));
     // -- Reddit
     if (profileData["contact_reddit"].Length > 0)
         contact.Append(Core.templates["bsa_profiles"]["profile_about_contact"]
             .Replace("<URL>", "http://www.reddit.com/user/" + HttpUtility.UrlEncode(profileData["contact_reddit"]))
             .Replace("<IMAGE>", "http://www.reddit.com/favicon.ico")
             .Replace("<TITLE>", HttpUtility.HtmlEncode(profileData["contact_reddit"])));
     // -- Steam
     if (profileData["contact_steam"].Length > 0)
         contact.Append(Core.templates["bsa_profiles"]["profile_about_contact"]
             .Replace("<URL>", "http://steamcommunity.com/id/" + HttpUtility.HtmlEncode(profileData["contact_steam"]))
             .Replace("<IMAGE>", "http://steamcommunity.com/favicon.ico")
             .Replace("<TITLE>", HttpUtility.HtmlEncode(profileData["contact_steam"])));
     // -- WLM
     if (profileData["contact_wlm"].Length > 0)
         contact.Append(Core.templates["bsa_profiles"]["profile_about_contact"]
             .Replace("<URL>", "http://spaces.live.com/profile.aspx?mem=" + HttpUtility.HtmlEncode(profileData["contact_wlm"]))
             .Replace("<IMAGE>", "http://windows.microsoft.com/favicon.ico")
             .Replace("<TITLE>", HttpUtility.HtmlEncode(profileData["contact_wlm"])));
     // -- Skype
     if (profileData["contact_skype"].Length > 0)
         contact.Append(Core.templates["bsa_profiles"]["profile_about_contact"]
             .Replace("<URL>", "http://myskype.info/" + HttpUtility.HtmlEncode(profileData["contact_skype"]))
             .Replace("<IMAGE>", "http://www.skypeassets.com/i/images/icons/favicon.ico")
             .Replace("<TITLE>", HttpUtility.HtmlEncode(profileData["contact_skype"])));
     // -- YouTube
     if (profileData["contact_youtube"].Length > 0)
         contact.Append(Core.templates["bsa_profiles"]["profile_about_contact"]
             .Replace("<URL>", "http://www.youtube.com/user/" + HttpUtility.HtmlEncode(profileData["contact_youtube"]))
             .Replace("<IMAGE>", "http://www.youtube.com/favicon.ico")
             .Replace("<TITLE>", HttpUtility.HtmlEncode(profileData["contact_youtube"])));
     // -- SoundCloud
     if (profileData["contact_soundcloud"].Length > 0)
         contact.Append(Core.templates["bsa_profiles"]["profile_about_contact"]
             .Replace("<URL>", "http://soundcloud.com/" + HttpUtility.HtmlEncode(profileData["contact_soundcloud"]))
             .Replace("<IMAGE>", "http://soundcloud.com/favicon.ico")
             .Replace("<TITLE>", HttpUtility.HtmlEncode(profileData["contact_soundcloud"])));
     // -- Xbox
     if (profileData["contact_xbox"].Length > 0)
         contact.Append(Core.templates["bsa_profiles"]["profile_about_contact"]
             .Replace("<URL>", "http://www.xboxlc.com/profile/" + HttpUtility.HtmlEncode(profileData["contact_xbox"]))
             .Replace("<IMAGE>", "http://www.xbox.com/favicon.ico")
             .Replace("<TITLE>", HttpUtility.HtmlEncode(profileData["contact_xbox"])));
     // -- PSN
     if (profileData["contact_psn"].Length > 0)
         contact.Append(Core.templates["bsa_profiles"]["profile_about_contact"]
             .Replace("<URL>", "http://profiles.us.playstation.com/playstation/psn/visit/profiles/" + HttpUtility.HtmlEncode(profileData["contact_psn"]))
             .Replace("<IMAGE>", "http://us.playstation.com/favicon.ico")
             .Replace("<TITLE>", HttpUtility.HtmlEncode(profileData["contact_psn"])));
     // -- Flickr
     if (profileData["contact_flickr"].Length > 0)
         contact.Append(Core.templates["bsa_profiles"]["profile_about_contact"]
             .Replace("<URL>", "http://www.flickr.com/photos/" + HttpUtility.HtmlEncode(profileData["contact_flickr"]))
             .Replace("<IMAGE>", "http://l.yimg.com/g/favicon.ico")
             .Replace("<TITLE>", HttpUtility.HtmlEncode(profileData["contact_flickr"])));
     // -- Twitter
     if (profileData["contact_twitter"].Length > 0)
         contact.Append(Core.templates["bsa_profiles"]["profile_about_contact"]
             .Replace("<URL>", "http://twitter.com/" + HttpUtility.HtmlEncode(profileData["contact_twitter"]))
             .Replace("<IMAGE>", "http://www.twitter.com/favicon.ico")
             .Replace("<TITLE>", HttpUtility.HtmlEncode(profileData["contact_twitter"])));
     // -- Xfire
     if (profileData["contact_xfire"].Length > 0)
         contact.Append(Core.templates["bsa_profiles"]["profile_about_contact"]
             .Replace("<URL>", "http://www.xfire.com/profile/" + HttpUtility.HtmlEncode(profileData["contact_xfire"]))
             .Replace("<IMAGE>", "http://xfire.com/favicon.ico")
             .Replace("<TITLE>", HttpUtility.HtmlEncode(profileData["contact_xfire"])));
     // -- Deviantart
     if (profileData["contact_deviantart"].Length > 0)
         contact.Append(Core.templates["bsa_profiles"]["profile_about_contact"]
             .Replace("<URL>", "http://" + HttpUtility.HtmlEncode(profileData["contact_deviantart"]) + ".deviantart.com/")
             .Replace("<IMAGE>", "http://deviantart.com/favicon.ico")
             .Replace("<TITLE>", HttpUtility.HtmlEncode(profileData["contact_deviantart"])));
     // Set nutshell
     StringBuilder nutshell = new StringBuilder(HttpUtility.HtmlEncode(profileData["nutshell"]));
     if(nutshell.Length == 0)
         nutshell.Append("User has not specified a nutshell.");
     else
         Common.formatProvider_format(ref nutshell, request, response, conn, ref pageElements, true, true);
     // Set content
     pageElements["PROFILE_CONTENT"] = Core.templates["bsa_profiles"]["profile_about"]
         .Replace("<NUTSHELL>", nutshell.ToString())
         .Replace("<CONTACT>", contact.Length == 0 ? "User has not specified any contact details." : contact.ToString())
         ;
     pageElements.setFlag("PROFILE_ABOUT");
 }
예제 #59
0
        public static void pageProfile_Settings(string pluginid, ref string profileQuery, ref ResultRow profileData, Connector conn, ref Misc.PageElements pageElements, HttpRequest request, HttpResponse response)
        {
            bool updatedProfile = false;
            string error = null;
            // Add the JS colour-picker
            Misc.Plugins.addHeaderJS("/Content/JS/bsa_profiles/jscolor.js", ref pageElements);
            // Check for postback
            // -- Profile
            string profileEnabled = request.Form["profile_enabled"];
            string frameBgURL = request.Form["frame_bg_url"];
            string frameBgColour = request.Form["frame_bg_colour"];
            string paneBgColour = request.Form["pane_bg_colour"];
            string paneTextColour = request.Form["pane_text_colour"];
            // -- About You
            string nutshell = request.Form["nutshell"];
            string country = request.Form["country"];
            string gender = request.Form["gender"];
            string occupation = request.Form["occupation"];
            // -- Contact details
            string contactGithub = request.Form["contact_github"];
            string contactWebsite = request.Form["contact_website"];
            string contactEmail = request.Form["contact_email"];
            string contactFacebook = request.Form["contact_facebook"];
            string contactGooglePlus = request.Form["contact_googleplus"];
            string contactReddit = request.Form["contact_reddit"];
            string contactSteam = request.Form["contact_steam"];
            string contactWlm = request.Form["contact_wlm"];
            string contactSkype = request.Form["contact_skype"];
            string contactYouTube = request.Form["contact_youtube"];
            string contactSoundcloud = request.Form["contact_soundcloud"];
            string contactXbox = request.Form["contact_xbox"];
            string contactPsn = request.Form["contact_psn"];
            string contactFlickr = request.Form["contact_flickr"];
            string contactTwitter = request.Form["contact_twitter"];
            string contactXfire = request.Form["contact_xfire"];
            string contactDeviantArt = request.Form["contact_deviantart"];
            if (profileEnabled != null && frameBgURL != null && frameBgColour != null && paneBgColour != null && paneTextColour != null && nutshell != null &&
                country != null && gender != null && occupation != null && contactGithub != null && contactWebsite != null && contactEmail != null && contactFacebook != null &&
                contactGooglePlus != null && contactReddit != null && contactSteam != null && contactWlm != null && contactSkype != null && contactYouTube != null && contactSoundcloud != null &&
                contactXbox != null && contactPsn != null && contactFlickr != null && contactTwitter != null && contactXfire != null && contactDeviantArt != null)
            {
                // Validate form data
                const int maxNutshell = 800;
                const int maxOccupation = 35;
                const int maxContactItem = 40;
                // -- Profile
                if (profileEnabled != "0" && profileEnabled != "1") error = "Invalid profile-enabled value!";
                else if (frameBgURL.Length != 0 && !Common.Validation.validUrl(frameBgURL))
                    error = "Invalid frame background URL!";
                else if (frameBgColour.Length != 0 && !Common.Validation.validHex(frameBgColour))
                    error = "Invalid frame background colour!";
                else if (paneBgColour.Length != 0 && !Common.Validation.validHex(paneBgColour))
                    error = "Invalid pane background colour!";
                else if (paneTextColour.Length != 0 && !Common.Validation.validHex(paneTextColour))
                    error = "Invalid pane text colour!";
                // -- About You
                else if (nutshell.Length > maxNutshell)
                    error = "Nutshell cannot be greater than 800 characters in length!";
                else if ((country.Length != 0 && country.Length != 2) || (country.Length != 0 && Common.Country.getCountryTitle(country, conn) == null))
                    error = "Invalid country!";
                else if (gender != "0" && gender != "1" && gender != "2")
                    error = "Invalid gender!";
                else if (occupation.Length > maxOccupation)
                    error = "Invalid occupation!";
                // -- Contact details - we'll only validate size
                else if (contactGithub.Length > maxContactItem)
                    error = "Contact github cannot exceed " + maxContactItem + " characters!";
                else if (contactWebsite.Length != 0 && !Common.Validation.validUrl(contactWebsite))
                    error = "Invalid contact website!";
                else if (contactEmail.Length != 0 && !Common.Validation.validEmail(contactEmail))
                    error = "Invalid contact e-mail!";
                else if (contactFacebook.Length > maxContactItem)
                    error = "Contact Facebook cannot exceed " + maxContactItem + " characters!";
                else if (contactGooglePlus.Length > maxContactItem)
                    error = "Contact Google Plus cannot exceed " + maxContactItem + " characters!";
                else if (contactReddit.Length > maxContactItem)
                    error = "Contact Reddit cannot exceed " + maxContactItem + " characters!";
                else if (contactSteam.Length > maxContactItem)
                    error = "Contact Steam cannot exceed " + maxContactItem + " characters!";
                else if (contactWlm.Length > maxContactItem)
                    error = "Contact WLM cannot exceed " + maxContactItem + " characters!";
                else if (contactSkype.Length > maxContactItem)
                    error = "Contact Skype cannot exceed " + maxContactItem + " characters!";
                else if (contactYouTube.Length > maxContactItem)
                    error = "Contact YouTube cannot exceed " + maxContactItem + " characters!";
                else if (contactSoundcloud.Length > maxContactItem)
                    error = "Contact SoundCloud cannot exceed " + maxContactItem + " characters!";
                else if (contactXbox.Length > maxContactItem)
                    error = "Contact Xbox Live cannot exceed " + maxContactItem + " characters!";
                else if (contactPsn.Length > maxContactItem)
                    error = "Contact PlayStation Network cannot exceed " + maxContactItem + " characters!";
                else if (contactFlickr.Length > maxContactItem)
                    error = "Contact Flickr cannot exceed " + maxContactItem + " characters!";
                else if (contactTwitter.Length > maxContactItem)
                    error = "Contact Twitter cannot exceed " + maxContactItem + " characters!";
                else if (contactXfire.Length > maxContactItem)
                    error = "Contact Xfire cannot exceed " + maxContactItem + " characters!";
                else if (contactDeviantArt.Length > maxContactItem)
                    error = "Contact DeviantArt cannot exceed " + maxContactItem + " characters!";
                else
                {
                    // Posted data is valid - update the database
                    try
                    {
                        StringBuilder query = new StringBuilder("UPDATE bsa_profiles SET ")
                        .Append("disabled='").Append(Utils.Escape(profileEnabled)).Append("',")
                        .Append("background_url='").Append(Utils.Escape(frameBgURL)).Append("',")
                        .Append("background_colour='").Append(Utils.Escape(frameBgColour)).Append("',")
                        .Append("colour_background='").Append(Utils.Escape(paneBgColour)).Append("',")
                        .Append("colour_text='").Append(Utils.Escape(paneTextColour)).Append("',")
                        .Append("nutshell='").Append(Utils.Escape(nutshell)).Append("',")
                        .Append("gender='").Append(Utils.Escape(gender)).Append("',")
                        .Append("country_code=").Append(country.Length == 0 ? "NULL" : "'" + Utils.Escape(country) + "'").Append(",")
                        .Append("occupation='").Append(Utils.Escape(occupation)).Append("',")
                        .Append("contact_github='").Append(Utils.Escape(contactGithub)).Append("',")
                        .Append("contact_website='").Append(Utils.Escape(contactWebsite)).Append("',")
                        .Append("contact_email='").Append(Utils.Escape(contactEmail)).Append("',")
                        .Append("contact_facebook='").Append(Utils.Escape(contactFacebook)).Append("',")
                        .Append("contact_reddit='").Append(Utils.Escape(contactReddit)).Append("',")
                        .Append("contact_googleplus='").Append(Utils.Escape(contactGooglePlus)).Append("',")
                        .Append("contact_steam='").Append(Utils.Escape(contactSteam)).Append("',")
                        .Append("contact_wlm='").Append(Utils.Escape(contactWlm)).Append("',")
                        .Append("contact_skype='").Append(Utils.Escape(contactSkype)).Append("',")
                        .Append("contact_youtube='").Append(Utils.Escape(contactYouTube)).Append("',")
                        .Append("contact_soundcloud='").Append(Utils.Escape(contactSoundcloud)).Append("',")
                        .Append("contact_xbox='").Append(Utils.Escape(contactXbox)).Append("',")
                        .Append("contact_psn='").Append(Utils.Escape(contactPsn)).Append("',")
                        .Append("contact_flickr='").Append(Utils.Escape(contactFlickr)).Append("',")
                        .Append("contact_twitter='").Append(Utils.Escape(contactTwitter)).Append("',")
                        .Append("contact_xfire='").Append(Utils.Escape(contactXfire)).Append("',")
                        .Append("contact_deviantart='").Append(Utils.Escape(contactDeviantArt)).Append("'")
                        .Append(" WHERE profileid='").Append(Utils.Escape(profileData["profileid"])).Append("'")
                        ;
                        conn.Query_Execute(query.ToString());
                        updatedProfile = true;
                        // Reload the profile settings
                        profileData = conn.Query_Read(profileQuery)[0];
                    }
                    catch
                    {
                        error = "Failed to update profile settings, try again!";
                    }
                }
            }
            // Build options
            StringBuilder profileEnabledItems = new StringBuilder();
            profileEnabledItems.Append("<option value=\"0\"").Append("0" == (profileEnabled ?? profileData["disabled"]) ? " selected=\"selected\"" : string.Empty).Append(">Enabled</option>");
            profileEnabledItems.Append("<option value=\"1\"").Append("1" == (profileEnabled ?? profileData["disabled"]) ? " selected=\"selected\"" : string.Empty).Append(">Disabled</option>");

            StringBuilder countryItems = new StringBuilder();
            countryItems.Append("<option value=\"\">Unknown</option>");
            foreach (Common.Country c in Common.Country.getCountries(conn))
                countryItems.Append("<option value=\"").Append(c.countryCode).Append("\"").Append(c.countryCode == (country ?? profileData["country_code"]) ? " selected=\"selected\"" : string.Empty).Append(">").Append(HttpUtility.HtmlEncode(c.countryTitle)).Append("</option>");

            StringBuilder genderItems = new StringBuilder();
            genderItems.Append("<option value=\"0\"").Append("0" == (gender ?? profileData["gender"]) ? " selected=\"selected\"" : string.Empty).Append(">Not Specified</option>");
            genderItems.Append("<option value=\"1\"").Append("1" == (gender ?? profileData["gender"]) ? " selected=\"selected\"" : string.Empty).Append(">Male</option>");
            genderItems.Append("<option value=\"2\"").Append("2" == (gender ?? profileData["gender"]) ? " selected=\"selected\"" : string.Empty).Append(">Female</option>");

            // Set the content
            pageElements["PROFILE_CONTENT"] = Core.templates["bsa_profiles"]["profile_settings"]
                .Replace("<USERID>", HttpUtility.HtmlEncode(profileData["userid"]))
                .Replace("<ERROR>", error != null ? Core.templates[pageElements["TEMPLATE"]]["error"].Replace("<ERROR>", HttpUtility.HtmlEncode(error)) : updatedProfile ? Core.templates[pageElements["TEMPLATE"]]["success"].Replace("<SUCCESS>", "Successfully updated profile settings!") : string.Empty)
                .Replace("<ENABLED>", profileEnabledItems.ToString())
                .Replace("<FRAME_BG_URL>", HttpUtility.HtmlEncode(profileData["background_url"]))
                .Replace("<FRAME_BG_COLOUR>", HttpUtility.HtmlEncode(profileData["background_colour"]))
                .Replace("<PANE_BG_COLOUR>", HttpUtility.HtmlEncode(profileData["colour_background"]))
                .Replace("<PANE_TEXT_COLOUR>", HttpUtility.HtmlEncode(profileData["colour_text"]))
                .Replace("<NUTSHELL>", HttpUtility.HtmlEncode(profileData["nutshell"]))
                .Replace("<COUNTRY>", countryItems.ToString())
                .Replace("<GENDER>", genderItems.ToString())
                .Replace("<OCCUPATION>", HttpUtility.HtmlEncode(profileData["occupation"]))
                .Replace("<CONTACT_GITHUB>", HttpUtility.HtmlEncode(profileData["contact_github"]))
                .Replace("<CONTACT_WEBSITE>", HttpUtility.HtmlEncode(profileData["contact_website"]))
                .Replace("<CONTACT_EMAIL>", HttpUtility.HtmlEncode(profileData["contact_email"]))
                .Replace("<CONTACT_FACEBOOK>", HttpUtility.HtmlEncode(profileData["contact_facebook"]))
                .Replace("<CONTACT_GOOGLEPLUS>", HttpUtility.HtmlEncode(profileData["contact_googleplus"]))
                .Replace("<CONTACT_REDDIT>", HttpUtility.HtmlEncode(profileData["contact_reddit"]))
                .Replace("<CONTACT_STEAM>", HttpUtility.HtmlEncode(profileData["contact_steam"]))
                .Replace("<CONTACT_WLM>", HttpUtility.HtmlEncode(profileData["contact_wlm"]))
                .Replace("<CONTACT_SKYPE>", HttpUtility.HtmlEncode(profileData["contact_skype"]))
                .Replace("<CONTACT_YOUTUBE>", HttpUtility.HtmlEncode(profileData["contact_youtube"]))
                .Replace("<CONTACT_SOUNDCLOUD>", HttpUtility.HtmlEncode(profileData["contact_soundcloud"]))
                .Replace("<CONTACT_XBOX>", HttpUtility.HtmlEncode(profileData["contact_xbox"]))
                .Replace("<CONTACT_PSN>", HttpUtility.HtmlEncode(profileData["contact_psn"]))
                .Replace("<CONTACT_FLICKR>", HttpUtility.HtmlEncode(profileData["contact_flickr"]))
                .Replace("<CONTACT_TWITTER>", HttpUtility.HtmlEncode(profileData["contact_twitter"]))
                .Replace("<CONTACT_XFIRE>", HttpUtility.HtmlEncode(profileData["contact_xfire"]))
                .Replace("<CONTACT_DEVIANTART>", HttpUtility.HtmlEncode(profileData["contact_deviantart"]))
                ;
            pageElements.setFlag("PROFILE_SETTINGS");
        }
예제 #60
0
 public void AddResultRow(ResultRow row) {
     this.Rows.Add(row);
 }