tag:blogger.com,1999:blog-23130718984270094362023-11-16T05:58:13.536-08:00dot remAnonymoushttp://www.blogger.com/profile/12444908737664761341noreply@blogger.comBlogger12125tag:blogger.com,1999:blog-2313071898427009436.post-16485950454698752912015-11-27T01:49:00.000-08:002015-11-27T01:49:41.406-08:00Простой AutoLoad LookUpEdit.<div dir="ltr" style="text-align: left;" trbidi="on">
<p>Возникла задача загружать в LookUpEdit значения постепенно, в зависимости от подстроки.<br>
Простейшее решение было найдено на сайте самого <a href="https://www.devexpress.com/Support/Center/Example/Details/E3132">DX</a>. Решение прекрасно работает, но дело в том, что поиск в LookUpEdit не поддерживает contains и ищет с начала строки. В примере это решено дописыванием к началу строки искомой подстроки:<br></p>
<pre class="brush:php;">
private void GetAutoCompleteList(AutoCompleteListEventArgs e) {
e.AutoCompleteList.Clear();
for(int i = 0; i < 10; i++) {
e.AutoCompleteList.Add(String.Format("{0}{1}", e.AutoSearchText, RandomString(5, true)));
}
}
</pre>
Выглядит это некрасиво. Поэтому что бы не показывать лишние данные нужно внедрить contains.<br>
Для этого переопределим DataAdapter. Пример на VB был найдет <a href="https://www.devexpress.com/Support/Center/Question/Details/Q348891">здесь</a> и осталось только переписать его на C#.</p><br>
<p>
Сам DataAdapter:
<pre class="brush:php;">
public class MyLookUpListDataAdapter : LookUpListDataAdapter
{
public MyLookUpListDataAdapter(AutoCompleteLookUpEditRepositoryItem item) : base(item)
{
}
public override string FilterField
{
get
{
if ((Item as AutoCompleteLookUpEditRepositoryItem).FilterField == string.Empty)
{
return base.FilterField;
}
return (Item as AutoCompleteLookUpEditRepositoryItem).FilterField;
}
}
protected override string CreateFilterExpression()
{
dynamic foo = FilterField;
if (string.IsNullOrEmpty(FilterPrefix))
{
return string.Empty;
}
string likeClause = DevExpress.Data.Filtering.Helpers.LikeData.CreateStartsWithPattern(FilterPrefix);
return new BinaryOperator(FilterField, "%" + likeClause + "%", BinaryOperatorType.Like).ToString();
}
}
</pre>
Так нужно внести изменения в класс AutoCompleteLookUpEditRepositoryItem:
<pre class="brush:php;">
public string FilterField { set; get; }
protected override LookUpListDataAdapter CreateDataAdapter()
{
return new MyLookUpListDataAdapter(this);
}
</pre>
<br /></div>
Anonymoushttp://www.blogger.com/profile/12444908737664761341noreply@blogger.com0tag:blogger.com,1999:blog-2313071898427009436.post-68826301375927260742015-02-10T05:34:00.000-08:002015-02-10T05:37:53.068-08:00Simple Excel report generation with OpenXML. <style>
p {
text-indent: 20px; /* Отступ первой строки в пикселах */
}
</style>
<div dir="ltr" style="text-align: left;" trbidi="on">
<br />
<p>I'd needed in simple solution to export a search results into Excel in .net application.<br>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjO1B5SorqIif1TAmDPUmoXVjLqXcayXNpGE0i8WxPq78uZlWlUDSFU1AvOPSt2FkKqdLlw2NOPiuegY-2jfeGY1hHPAgRDIhJS_L1sbuscnYolGMJKOKdRK8bDT9VtIJwuPu0m7risHwc/s1600/excel_report.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjO1B5SorqIif1TAmDPUmoXVjLqXcayXNpGE0i8WxPq78uZlWlUDSFU1AvOPSt2FkKqdLlw2NOPiuegY-2jfeGY1hHPAgRDIhJS_L1sbuscnYolGMJKOKdRK8bDT9VtIJwuPu0m7risHwc/s400/excel_report.jpg" /></a></div>
At first i create ViewModel using simple types only:
<pre class="brush:php;">
public class MyReportItem
{
public string ObjectType{ get; set; }
public string Name{ get; set; }
public string Owner{ get; set; }
public string District{ set; get; }
public string Street{ set; get; }
public string Address{ get; set; }
public string ObjectContacts{ get; set; }
public string Specilization{ get; set; }
}
</pre>
</p>
<p>My objective - create a simple report so i don't want use document template. So i create excel document by OpenXML in stream.
<pre class="brush:php">
public MemoryStream CreateReport(List<MyReportItem> report)
{
using (var reader = new MemoryStream())
{
var spreadsheetDocument = SpreadsheetDocument.
Create(reader, SpreadsheetDocumentType.Workbook);
var workbookpart = spreadsheetDocument.AddWorkbookPart();
workbookpart.Workbook = new Workbook();
var stylesPart = spreadsheetDocument.WorkbookPart.AddNewPart<WorkbookStylesPart>();
stylesPart.Stylesheet = GenerateStyleSheet();
stylesPart.Stylesheet.Save();
var worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
var sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild(new Sheets());
var sheet = new Sheet
{
Id = spreadsheetDocument.WorkbookPart.
GetIdOfPart(worksheetPart),
SheetId = 1,
Name = "My sheet"
};
sheets.Append(sheet);
var sd = new SheetData();
var ws = new Worksheet();
var columns = new Columns();
columns.Append(CreateColumnData(1, 35, 30));
ws.Append(columns);
ws.Append(sd);
worksheetPart.Worksheet = ws;
GenerateColumnsCaptions(ws, report);
workbookpart.Workbook.Save();
spreadsheetDocument.Close();
return reader;
}
</pre>
</p>
<p>Part with columns not required but i want to set a columns width. and here is method to add <b>Column</b>to <b>Columns</b>:<br>
<pre class="brush:php">
public static Column CreateColumnData(UInt32 startColumnIndex, UInt32 endColumnIndex, double columnWidth)
{
var column = new Column
{
Min = startColumnIndex,
Max = endColumnIndex,
Width = columnWidth,
CustomWidth = true
};
return column;
}
</pre>
</p>
<p><i>Here is interesting thing. Columns in Excel table make only visual aspect of table, for setting widht of cells in this column. More, if your cell have a address <b>A4</b> it's mean that cell located in fourth row, and in this row this cell located on foremost. Columns not binded this cell.</i> </p>
<p>So now we have a empty document, let's fill it with data:<br>
<pre class="brush:php">
public Worksheet GenerateColumnsCaptions(Worksheet ws, ReportExcel report)
{
var sheetData = ws.GetFirstChild<SheetData>();
uint rowIntIter = 1; //row iterator
var colCharIter = 'A'; //column iterator
var row = new Row { RowIndex = 1 };
var fields = typeof (MyReportItem).GetFields(
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
var names = Array.ConvertAll(fields, field => field.Name).ToList();
var trimedNames = names.Select(name => name.Substring(1, name.IndexOf(">", StringComparison.Ordinal)-1)).ToList();
foreach (var fieldName in trimedNames)
{
var newCell = new Cell { CellReference = colCharIter + rowIntIter.ToString(CultureInfo.InvariantCulture), StyleIndex = 1 };
row.AppendChild(newCell);
newCell.CellValue = new CellValue(fieldName);
newCell.DataType = new EnumValue<CellValues>(CellValues.String);
colCharIter++; // next column
}
sheetData.Append(row);
colCharIter = 'A'; // reset column iterator
foreach (var объект in report.Объекты)
{
rowIntIter++; // next row
var rowItem = new Row { RowIndex = rowIntIter };
Type t = объект.Объект.GetType();
foreach (PropertyInfo info in t.GetProperties())
{
var value = info.GetValue(объект.Объект, null);
var valueStr = "-";
if (value != null)
{
valueStr = value.ToString();
if (value is DateTime)
{
var date = (DateTime)value;
valueStr = date.ToShortDateString();
}
if (value is bool)
{
var date = (bool)value;
valueStr = date ? "Yes" : "No";
}
}
rowItem.AppendChild(ReportsRoutines.CreateCell(valueStr, colCharIter + rowIntIter.ToString(CultureInfo.InvariantCulture)));
colCharIter++;
}
sheetData.Append(rowItem);
colCharIter = 'A'; // finished with this object so reset column iterator
}
return ws;
}
</pre>
</p>
<p>At first create row with columns captions:<br>
<pre class="brush:php">
var colCharIter = 'A';
var row = new Row { RowIndex = 1 };
var fields = typeof (MyReportItem).GetFields(
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
var names = Array.ConvertAll(fields, field => field.Name).ToList();
var trimedNames = names.Select(name => name.Substring(1, name.IndexOf(">", StringComparison.Ordinal)-1)).ToList();
foreach (var fieldName in trimedNames)
{
var newCell = new Cell { CellReference = colCharIter + rowIntIter.ToString(CultureInfo.InvariantCulture), StyleIndex = 1 };
row.AppendChild(newCell);
newCell.CellValue = new CellValue(fieldName);
newCell.DataType = new EnumValue<CellValues>(CellValues.String);
colCharIter++;
}
sheetData.Append(row);
</pre>
</p>
<p>Here i collect my view model's fields names and after trimming garabage setting it one by one in row's cells. Fields are taken in the order in which they appear in class. And if you waht to reorder columns you need just reorder fields in class.</p>
<p>After i getting started to fill document with data:<br>
<pre class="brush:php">
colCharIter = 'A';
foreach (var obj in report)
{
rowIntIter++;
var rowItem = new Row { RowIndex = rowIntIter };
Type t = obj .GetType();
foreach (PropertyInfo info in t.GetProperties())
{
var value = info.GetValue(obj, null);
var valueStr = "-";
if (value != null)
{
valueStr = value.ToString();
if (value is DateTime)
{
var date = (DateTime)value;
valueStr = date.ToShortDateString();
}
if (value is bool)
{
var date = (bool)value;
valueStr = date ? "Yes" : "No";
}
}
rowItem.AppendChild(ReportsRoutines.CreateCell(valueStr, colCharIter + rowIntIter.ToString(CultureInfo.InvariantCulture)));
colCharIter++;
}
sheetData.Append(rowItem);
colCharIter = 'A';
}
</pre>
</p>
<p>Here i iterate through view model fileds and take it's values.<br>
</p>
<p>
After you can save document using something like:<br>
<pre class="brush:php">
var saveFileDialog = new SaveFileDialog { Filter = "*.xlsx|*.xlsx", Title = "Save as..." };
File.WriteAllBytes(saveFileDialog.FileName, reader.ToArray());
</pre>
</p>
</div>
Anonymoushttp://www.blogger.com/profile/12444908737664761341noreply@blogger.com0tag:blogger.com,1999:blog-2313071898427009436.post-26033357269809929522014-11-23T10:19:00.001-08:002014-11-23T10:19:15.957-08:00Копирование элементов макета печати ИнГео. <style>
p {
text-indent: 20px; /* Отступ первой строки в пикселах */
}
</style>
<div dir="ltr" style="text-align: left;" trbidi="on">
<p align="justify">Работа с макетом печати не очень хорошо освещена в документации к ИнГео, что странно, потому как по крайней мере мне показалась реализация макета печати не очень нативной. И это даже на пользовательском уровне, например работа с таблицами вообще аттас.<br>
Ну да ладно, все это преодолимо. Более интересная задача с которой пришлось столкнутся - это создание макета программно.</p>
<p>Но прежде скажу некоторые детали. В макет печати можно включить несколько видов объектов:<br>
<ul>
<li>Карта</li>
<li>Прямоугольник</li>
<li>Эллипс</li>
<li>Линия</li>
<li>Рисунок</li>
<li>Текст</li>
<li>Таблица</li>
</ul>
<br>
Вот например макет состоящий из участка карты и таблицы:</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjbs6hoEnOCEOI4fmhLH7qRdGloRGorMGyp0Qw7-6MbVaKxKRAdDPRzN_FHJVa7Gh9V66yzEa2tPh8uOoOJn5U6eXMJRxbKf2y5HVqedAy9ARPjSLlVCkhCwQtuzOx7X-SWvSJoxVYPYqM/s1600/maket_1.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjbs6hoEnOCEOI4fmhLH7qRdGloRGorMGyp0Qw7-6MbVaKxKRAdDPRzN_FHJVa7Gh9V66yzEa2tPh8uOoOJn5U6eXMJRxbKf2y5HVqedAy9ARPjSLlVCkhCwQtuzOx7X-SWvSJoxVYPYqM/s400/maket_1.jpg" /></a></div>
<br>
<p align="justify">Теперь займемся клонированием объектов макета. Начнем с простого - с Рисунка. Нужно взять копируемый объект из макета и затем создать новый, пустой рисунок:</br>
<pre class="brush:php;">
var sourceImage = (IInPicturePictureFigure)MyLayoutWindow.Figures.Find("imageName");
var targetImage = MyLayoutWindow.Figures.Add(TInPictureFigureType.inftPicture) as IInPicturePictureFigure;
СкопироватьРисунок(targetImage , sourceImage );
</pre>
А вот и сам метод для копирования:<br>
<pre class="brush:php;">
//Рисунок
public static IInPicturePictureFigure СкопироватьРисунок(IInPicturePictureFigure target, IInPicturePictureFigure source)
{
target.Width = source.Width;
target.Height = source.Height;
target.Picture = source.Picture;
target.Stretch = source.Stretch;
target.HorAlign = source.HorAlign;
target.VerAlign = source.VerAlign;
target.TransparentBack = source.TransparentBack;
target.Pen.Mode = source.Pen.Mode;
target.Pen.Style = source.Pen.Style;
target.Pen.WidthInMM = source.Pen.WidthInMM;
target.Pen.Color = source.Pen.Color;
target.Brush.HatchColor = source.Brush.HatchColor;
target.Brush.BackColor = source.Brush.BackColor;
target.Brush.Transparency = source.Brush.Transparency;
target.Brush.Style = source.Brush.Style;
return target;
}
</pre>
</p>
<p align="justify">Как видите метод копирует свойства объекта из существующего в новый. Уже после такого копирования можно установить положение объекта на карте пользуясь свойствами <b>Bottom</b> и <b>Left</b>.<br>
Для остальных объектов макета печати используются аналогичные методы поэтому приведу еще один пример для Прямоугольника:</br>
<pre class="brush:php;">
//Прямоугольник
public static IInPictureRectFigure СкопироватьПрямоугольник(IInPictureRectFigure target, IInPictureRectFigure source)
{
target.Width = source.Width;
target.Height = source.Height;
target.Pen.Mode = source.Pen.Mode;
target.Pen.Style = source.Pen.Style;
target.Pen.WidthInMM = source.Pen.WidthInMM;
target.Pen.Color = source.Pen.Color;
target.Brush.HatchColor = source.Brush.HatchColor;
target.Brush.BackColor = source.Brush.BackColor;
target.Brush.Transparency = source.Brush.Transparency;
target.Brush.Style = source.Brush.Style;
return target;
}
</pre>
</p>
<p align="justify">Немного по другому обстоит дело с Таблицей. Дело в том, что у этого объекта есть два набора параметров: дефолтные - находятся в левой панели, и специальные - находится в контекстном меню в <b>Редакторе таблицы</b>.<br>
Дефолтные настройки позволяют настроить таблицу в целом, а так же сделать стиль по умолчанию, который будет применяться ко всем строкам/столбцам/ячейкам. Поэтому если нужно создать таблицу с неизвестного в заранее размера, то стиль нужно задавать именно в левой панели.<br>
Но у шапки таблицы, стиль обычно отличен от стиля остальных ячеек, например первая строка может быть написана болдом или иметь цветовую заливку. Тут в дело вступает <b>Редактор таблицы</b>, он позволяет настроить каждую отдельную строку, колонку или ячейку по своему. Кроме того стандартный текст, для той же шапки таблицы, то же указывается в <b>Редакторе</b>.
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgaHBquLO1qEU8xsrGs1F0b2APCr6Z8eUb_l8UxRr1vSxliUXLHIN7kxg3K9mI3pYu8qQ_9t74KRvtpKL4d6FeebkZOCbtkWb_LIubnBdNv4SlF6y0gDmWGj2PIb2XzT1bugCMMgx6L2Hg/s1600/maket_2.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgaHBquLO1qEU8xsrGs1F0b2APCr6Z8eUb_l8UxRr1vSxliUXLHIN7kxg3K9mI3pYu8qQ_9t74KRvtpKL4d6FeebkZOCbtkWb_LIubnBdNv4SlF6y0gDmWGj2PIb2XzT1bugCMMgx6L2Hg/s400/maket_2.jpg" /></a></div>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgsr1BYwdWGj00oJLhUyS1nvZQBwEhrg9iDKGCfagTlMd20eJJ87VSqGnPSKTvOGf06u7xNYs_Ce-KCVH-E1GEDVzzeSUgEt2_Kt8T0u38K3plLAGwEO92P5Uf2OfBXxfZNJXTdYkQVtmk/s1600/maket_3.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgsr1BYwdWGj00oJLhUyS1nvZQBwEhrg9iDKGCfagTlMd20eJJ87VSqGnPSKTvOGf06u7xNYs_Ce-KCVH-E1GEDVzzeSUgEt2_Kt8T0u38K3plLAGwEO92P5Uf2OfBXxfZNJXTdYkQVtmk/s400/maket_3.jpg" /></a></div>
Получается чтобы полностью скопировать стиль таблицы нужно копировать два набора параметров.<br>
<pre class="brush:php;">
//Таблица
public static IInPictureGridFigure СкопироватьТаблицу(IInPictureGridFigure target, IInPictureGridFigure source)
{
target.ColCount = source.ColCount;
target.RowCount = source.RowCount;
target.Width = source.Width;
target.Height = source.Height;
var targetGridFormat = target.GridFormat;
var sourceGridFormat = source.GridFormat;
if (sourceGridFormat.ContainsKinds(TInGridFormatKind.ingfLeftPen))
{
targetGridFormat = СкопироватьЭлементPen(TInGridFormatKind.ingfLeftPen, targetGridFormat, sourceGridFormat);
}
if (sourceGridFormat.ContainsKinds(TInGridFormatKind.ingfRightPen))
{
targetGridFormat = СкопироватьЭлементPen(TInGridFormatKind.ingfRightPen, targetGridFormat, sourceGridFormat);
}
if (sourceGridFormat.ContainsKinds(TInGridFormatKind.ingfTopPen))
{
targetGridFormat = СкопироватьЭлементPen(TInGridFormatKind.ingfTopPen, targetGridFormat, sourceGridFormat);
}
if (sourceGridFormat.ContainsKinds(TInGridFormatKind.ingfBottomPen))
{
targetGridFormat = СкопироватьЭлементPen(TInGridFormatKind.ingfBottomPen, targetGridFormat, sourceGridFormat);
}
targetGridFormat.Update();
for (int i = 0; i < source.ColCount; i++)
{
var targetColumnFormat = target.GetFormat(i, -1);
var sourceColumnFormat = source.GetFormat(i, -1);
var defaultSourceColumnFormat = source.ColFormat;
var defaultTargetColumnFormat = target.ColFormat;
if (sourceColumnFormat.ContainsKinds(TInGridFormatKind.ingfColWidth))
{
targetColumnFormat = СкопироватьЭлементSize(TInGridFormatKind.ingfColWidth, targetColumnFormat, sourceColumnFormat);
}
else
{
defaultTargetColumnFormat = СкопироватьЭлементSize(TInGridFormatKind.ingfColWidth, defaultTargetColumnFormat, defaultSourceColumnFormat);
}
if (sourceColumnFormat.ContainsKinds(TInGridFormatKind.ingfFont))
{
targetColumnFormat = СкопироватьЭлементFont(TInGridFormatKind.ingfFont, targetColumnFormat, sourceColumnFormat);
}
if (sourceColumnFormat.ContainsKinds(TInGridFormatKind.ingfTextFormat))
{
targetColumnFormat = СкопироватьЭлементTextFormat(TInGridFormatKind.ingfFont, targetColumnFormat, sourceColumnFormat);
}
if (sourceColumnFormat.ContainsKinds(TInGridFormatKind.ingfLeftPen))
{
targetColumnFormat = СкопироватьЭлементPen(TInGridFormatKind.ingfLeftPen, targetColumnFormat, sourceColumnFormat);
}
else
{
defaultTargetColumnFormat = СкопироватьЭлементPen(TInGridFormatKind.ingfLeftPen, defaultTargetColumnFormat, defaultSourceColumnFormat);
}
if (sourceColumnFormat.ContainsKinds(TInGridFormatKind.ingfRightPen))
{
targetColumnFormat = СкопироватьЭлементPen(TInGridFormatKind.ingfRightPen, targetColumnFormat, sourceColumnFormat);
}
else
{
defaultTargetColumnFormat = СкопироватьЭлементPen(TInGridFormatKind.ingfRightPen, defaultTargetColumnFormat, defaultSourceColumnFormat);
}
if (sourceColumnFormat.ContainsKinds(TInGridFormatKind.ingfTopPen))
{
targetColumnFormat = СкопироватьЭлементPen(TInGridFormatKind.ingfTopPen, targetColumnFormat, sourceColumnFormat);
}
else
{
defaultTargetColumnFormat = СкопироватьЭлементPen(TInGridFormatKind.ingfTopPen, defaultTargetColumnFormat, defaultSourceColumnFormat);
}
if (sourceColumnFormat.ContainsKinds(TInGridFormatKind.ingfBottomPen))
{
targetColumnFormat = СкопироватьЭлементPen(TInGridFormatKind.ingfBottomPen, targetColumnFormat, sourceColumnFormat);
}
else
{
defaultTargetColumnFormat = СкопироватьЭлементPen(TInGridFormatKind.ingfBottomPen, defaultTargetColumnFormat, defaultSourceColumnFormat);
}
defaultTargetColumnFormat.Update();
targetColumnFormat.Update();
}
for (int i = 0; i < source.RowCount; i++)
{
var targetRowFormat = target.GetFormat(-1, i);
var sourceRowFormat = source.GetFormat(-1, i);
var defaultSourceRowFormat = source.RowFormat;
var defaultTargetRowFormat = target.RowFormat;
if (sourceRowFormat.ContainsKinds(TInGridFormatKind.ingfRowHeight))
{
targetRowFormat = СкопироватьЭлементSize(TInGridFormatKind.ingfColWidth, targetRowFormat, sourceRowFormat);
}
else
{
defaultTargetRowFormat = СкопироватьЭлементSize(TInGridFormatKind.ingfColWidth, defaultTargetRowFormat, defaultSourceRowFormat);
}
if (sourceRowFormat.ContainsKinds(TInGridFormatKind.ingfFont))
{
targetRowFormat = СкопироватьЭлементFont(TInGridFormatKind.ingfFont, targetRowFormat, sourceRowFormat);
}
if (sourceRowFormat.ContainsKinds(TInGridFormatKind.ingfTextFormat))
{
targetRowFormat = СкопироватьЭлементTextFormat(TInGridFormatKind.ingfFont, targetRowFormat, sourceRowFormat);
}
if (sourceRowFormat.ContainsKinds(TInGridFormatKind.ingfLeftPen))
{
targetRowFormat = СкопироватьЭлементPen(TInGridFormatKind.ingfLeftPen, targetRowFormat, sourceRowFormat);
}
else
{
defaultTargetRowFormat = СкопироватьЭлементPen(TInGridFormatKind.ingfLeftPen, defaultTargetRowFormat, defaultSourceRowFormat);
}
if (sourceRowFormat.ContainsKinds(TInGridFormatKind.ingfRightPen))
{
targetRowFormat = СкопироватьЭлементPen(TInGridFormatKind.ingfRightPen, targetRowFormat, sourceRowFormat);
}
else
{
defaultTargetRowFormat = СкопироватьЭлементPen(TInGridFormatKind.ingfRightPen, defaultTargetRowFormat, defaultSourceRowFormat);
}
if (sourceRowFormat.ContainsKinds(TInGridFormatKind.ingfTopPen))
{
targetRowFormat = СкопироватьЭлементPen(TInGridFormatKind.ingfTopPen, targetRowFormat, sourceRowFormat);
}
else
{
defaultTargetRowFormat = СкопироватьЭлементPen(TInGridFormatKind.ingfTopPen, defaultTargetRowFormat, defaultSourceRowFormat);
}
if (sourceRowFormat.ContainsKinds(TInGridFormatKind.ingfBottomPen))
{
targetRowFormat = СкопироватьЭлементPen(TInGridFormatKind.ingfBottomPen, targetRowFormat, sourceRowFormat);
}
else
{
defaultTargetRowFormat = СкопироватьЭлементPen(TInGridFormatKind.ingfBottomPen, defaultTargetRowFormat, defaultSourceRowFormat);
}
targetRowFormat.Update();
defaultTargetRowFormat.Update();
}
for (int i = 0; i < source.ColCount; i++)
{
for (int j = 0; j < source.RowCount; j++)
{
var targetCellFormat = target.GetFormat(i, j);
var sourceCellFormat = source.GetFormat(i, j);
var defaultSourceCellFormat = source.CellFormat;
var defaultTargetCellFormat = target.CellFormat;
if (sourceCellFormat.ContainsKinds(TInGridFormatKind.ingfFont))
{
targetCellFormat = СкопироватьЭлементFont(TInGridFormatKind.ingfFont, targetCellFormat, sourceCellFormat);
}
else
{
defaultTargetCellFormat = СкопироватьЭлементFont(TInGridFormatKind.ingfFont, defaultTargetCellFormat, defaultSourceCellFormat);
}
if (sourceCellFormat.ContainsKinds(TInGridFormatKind.ingfTextFormat))
{
targetCellFormat = СкопироватьЭлементTextFormat(TInGridFormatKind.ingfFont, targetCellFormat, sourceCellFormat);
}
else
{
defaultTargetCellFormat = СкопироватьЭлементTextFormat(TInGridFormatKind.ingfFont, defaultTargetCellFormat, defaultSourceCellFormat);
}
if (sourceCellFormat.ContainsKinds(TInGridFormatKind.ingfBrush))
{
targetCellFormat = СкопироватьЭлементBrush(TInGridFormatKind.ingfFont, targetCellFormat, sourceCellFormat);
}
else
{
defaultTargetCellFormat = СкопироватьЭлементBrush(TInGridFormatKind.ingfFont, defaultTargetCellFormat, defaultSourceCellFormat);
}
if (sourceCellFormat.ContainsKinds(TInGridFormatKind.ingfLeftIndent))
{
targetCellFormat = СкопироватьЭлементSize(TInGridFormatKind.ingfColWidth, targetCellFormat, sourceCellFormat);
}
else
{
defaultTargetCellFormat = СкопироватьЭлементSize(TInGridFormatKind.ingfColWidth, defaultTargetCellFormat, defaultSourceCellFormat);
}
targetCellFormat.Update();
defaultTargetCellFormat.Update();
}
}
for (int i = 0; i < source.ColCount; i++)
{
for (int j = 0; j < source.RowCount; j++)
{
target.Text[i, j] = source.Text[i, j];
}
}
return target;
}
</pre></p>
<p align="justify">Метод состоит из трех циклов по строкам (RowCount), столбцам (ColCount), и ячейкам. Для каждого элемента определяется есть ли у него специальный формат с помощью <b>ContainsKinds()</b>.
Если специальный формат есть, то в новую таблицу копируется он, если нет то копируется дефолтный формат. Для удобства методы копирования отдельных элементов формата вынесены в отдельные методы:<br>
<pre class="brush:php;">
private static IInGridFormat СкопироватьЭлементPen(TInGridFormatKind inGridFormatKind, IInGridFormat target, IInGridFormat source)
{
target.Pen[inGridFormatKind].Style = source.Pen[inGridFormatKind].Style;
target.Pen[inGridFormatKind].Color = source.Pen[inGridFormatKind].Color;
target.Pen[inGridFormatKind].Mode = source.Pen[inGridFormatKind].Mode;
target.Pen[inGridFormatKind].WidthInMM = source.Pen[inGridFormatKind].WidthInMM;
return target;
}
private static IInGridFormat СкопироватьЭлементFont(TInGridFormatKind inGridFormatKind, IInGridFormat target, IInGridFormat source)
{
target.Font[inGridFormatKind].Size = source.Font[inGridFormatKind].Size;
target.Font[inGridFormatKind].Style = source.Font[inGridFormatKind].Style;
return target;
}
private static IInGridFormat СкопироватьЭлементBrush(TInGridFormatKind inGridFormatKind, IInGridFormat target, IInGridFormat source)
{
target.Brush[TInGridFormatKind.ingfBrush].BackColor = source.Brush[TInGridFormatKind.ingfBrush].BackColor;
target.Brush[TInGridFormatKind.ingfBrush].HatchColor = source.Brush[TInGridFormatKind.ingfBrush].HatchColor;
target.Brush[TInGridFormatKind.ingfBrush].Transparency = source.Brush[TInGridFormatKind.ingfBrush].Transparency;
return target;
}
private static IInGridFormat СкопироватьЭлементSize(TInGridFormatKind inGridFormatKind, IInGridFormat target,
IInGridFormat source)
{
target.Size[inGridFormatKind] = source.Size[inGridFormatKind];
return target;
}
private static IInGridFormat СкопироватьЭлементTextFormat(TInGridFormatKind inGridFormatKind, IInGridFormat target,
IInGridFormat source)
{
target.TextFormat[inGridFormatKind] = source.TextFormat[inGridFormatKind];
return target;
}
</pre>
</p>
<p align="justify">В заключение скажу, что методы копирования не являются полными, я копировал только те элементы формата, которые использовались в моем макете печати.</p>
<br /></div>
Anonymoushttp://www.blogger.com/profile/12444908737664761341noreply@blogger.com0tag:blogger.com,1999:blog-2313071898427009436.post-87356339657708735002014-09-09T12:11:00.001-07:002014-09-09T12:11:24.518-07:00Кириллица в Mapfish print plugin.<div dir="ltr" style="text-align: left;" trbidi="on">
<br />
<p>Сразу же скажу, что способ приведенный ниже работает только в случае если надписи содержащие кириллицу приходят с клиента в виде параметров. Те надписи, которые захардкожены в конфиге печати все равно отображаются краказябрами. Если кто-то знает как это вылечить буду признателен за информацию.</p>
<p>Для отображения кириллицы я использую кодировку <b>Identity-H</b>. Но ее одной недостаточно, если попробовать напечатать такой пример:</p>
<pre class="brush:php;">
- !text
text: "Привет"
fontEncoding: Identity-H
align: center
</pre>
<p>То ничего не напечатается, будет просто пустое место.</br>
Для решения этой проблемы нужно подключить шрифт работающий с данной кодировкой. Мой выбор пал на <b><a href="http://www.fontspace.com/gnu-freefont/freesans">FreeSans</a></b></p>
<p>Подключаются шрифты в отдельном блоке:</br>
<pre class="brush:php;">
scales:
....
fonts:
- 'E:\GeoServer 2.5.1\data_dir\printing\FreeSans.ttf'
- 'E:\GeoServer 2.5.1\data_dir\printing\FreeSansOblique.ttf'
hosts:
....
layouts:
....
</pre>
Подключение шрифта к элементу:<br>
<pre class="brush:php;">
- !text
text: "Привет"
fontEncoding: Identity-H
font: FreeSans
align: center
</pre>
Теперь все должно работать.
</p>
<p>Так же скажу, что подключить шрифты к легенде мне не удалось. Легенда выводится криво - имена стилей показывают кириллицу ,а вот имена слоев нет.</br>
В работе использовалась связка Geoserver 2.5.2 и Print plugin 1.2</p>
</div>
Anonymoushttp://www.blogger.com/profile/12444908737664761341noreply@blogger.com0tag:blogger.com,1999:blog-2313071898427009436.post-18365375518339492142014-08-24T22:40:00.003-07:002014-08-24T22:41:52.842-07:00Rotation text in line's start point by attribute<div dir="ltr" style="text-align: left;" trbidi="on">
<p>I needed to create SLD style for lines with text rotation on angle equals line azimuth in start point of line. Like this:</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi4BFZjSihvVeTTiuhDY26k768GbyJPTH-5LIwKBM_kNar-n_S6FCwNPmYoKUM5Ppx1nZJX4eW7Pv2PR2gOBzdD56U12-Jm-NJrue8F_wj67fvTznKUZSophoxBBn-II08uGsj56xlzDx4/s1600/rot_line.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi4BFZjSihvVeTTiuhDY26k768GbyJPTH-5LIwKBM_kNar-n_S6FCwNPmYoKUM5Ppx1nZJX4eW7Pv2PR2gOBzdD56U12-Jm-NJrue8F_wj67fvTznKUZSophoxBBn-II08uGsj56xlzDx4/s320/rot_line.jpg" /></a></div>
<h1>Data</h1>
<p>My table creation script:</br>
<pre class="brush:php;">
CREATE TABLE annotations
(
gid serial NOT NULL,
annotation character varying(250),
the_geom geometry,
angle character varying(20) DEFAULT 0,
CONSTRAINT annotations_pkey PRIMARY KEY (gid),
CONSTRAINT enforce_dims_the_geom CHECK (st_ndims(the_geom) = 2),
CONSTRAINT enforce_srid_the_geom CHECK (st_srid(the_geom) = 4326)
)
WITH (
OIDS=FALSE
);
ALTER TABLE annotations
OWNER TO postgres;
</pre>
</p>
<p>"angle" field - contains line azimuth, to calculate it i use trigger:</br>
<pre class="brush:php;">
CREATE TRIGGER set_angle
BEFORE INSERT OR UPDATE
ON annotations
FOR EACH ROW
EXECUTE PROCEDURE setangle();
</pre>
</p>
<p>And function:</br>
<pre class="brush:php;">
CREATE OR REPLACE FUNCTION setangle()
RETURNS trigger AS
$BODY$
BEGIN
NEW.angle := degrees(
ST_Azimuth(
ST_Transform(ST_StartPoint(NEW.the_geom),900913)
, ST_Transform(ST_EndPoint(NEW.the_geom),900913)
)
) - 90;
RETURN NEW;
END
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION setangle()
OWNER TO postgres;
</pre>
</p>
<p>As you can notice my table SRID=4326, but in calculation points transform into SRID=900913. It's becouse my application map projection is <b>EPSG:900913</b>. If do not transform point to projection what you will show this table you get difference between line azimuth and angle field value:</br>
<div class="separator" style="clear: both; text-align: center;"><a href="http://i.stack.imgur.com/HaLyO.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://i.stack.imgur.com/HaLyO.jpg" /></a></div>
</p>
<h1>Style</h1>
<p>Here is my SLD style:<br>
<pre class="brush:php;">
<?xml version="1.0" encoding="utf-8"?>
<StyledLayerDescriptor version="1.0.0"
xsi:schemaLocation="http://www.opengis.net/sld StyledLayerDescriptor.xsd"
xmlns="http://www.opengis.net/sld"
xmlns:ogc="http://www.opengis.net/ogc"
xmlns:xlink="http://www.w3.org/1999/xlink"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<NamedLayer>
<Name>Annotatioans</Name>
<UserStyle>
<Title>Annotations</Title>
<Abstract>Annotations white text</Abstract>
<FeatureTypeStyle>
<Rule>
<TextSymbolizer>
<Geometry>
<ogc:Function name="startPoint">
<ogc:PropertyName>the_geom</ogc:PropertyName>
</ogc:Function>
</Geometry>
<Label>
<ogc:PropertyName>annotation</ogc:PropertyName>
</Label>
<Font>
<CssParameter name="font-family">Arial</CssParameter>
<CssParameter name="font-size"><ogc:PropertyName>fontSize</ogc:PropertyName></CssParameter>
<CssParameter name="font-style">normal</CssParameter>
<CssParameter name="font-weight">bold</CssParameter>
</Font>
<LabelPlacement>
<PointPlacement>
<AnchorPoint>
<AnchorPointX>0.0</AnchorPointX>
<AnchorPointY>0.5</AnchorPointY>
</AnchorPoint>
<Displacement>
<DisplacementX>0</DisplacementX>
<DisplacementY>5</DisplacementY>
</Displacement>
<Rotation>
<ogc:PropertyName>rotationAngle</ogc:PropertyName>
</Rotation>
</PointPlacement>
</LabelPlacement>
<Halo>
<Radius>1</Radius>
<Fill>
<CssParameter name="fill">#000000</CssParameter>
</Fill>
</Halo>
<Fill>
<CssParameter name="fill">#FFFFFF</CssParameter>
</Fill>
<VendorOption name="spaceAround">10</VendorOption>
<VendorOption name="group">yes</VendorOption>
</TextSymbolizer>
<LineSymbolizer>
<Stroke>
<CssParameter name="stroke">#000000</CssParameter>
</Stroke>
</LineSymbolizer>
</Rule>
</FeatureTypeStyle>
</UserStyle>
</NamedLayer>
</StyledLayerDescriptor>
</pre>
</p>
<p>Main part here is <b>Rotation</b> block:<br>
<pre class="brush:php;">
<Rotation>
<ogc:PropertyName>rotationAngle</ogc:PropertyName>
</Rotation>
</pre>
<br /></div>
Anonymoushttp://www.blogger.com/profile/12444908737664761341noreply@blogger.com0tag:blogger.com,1999:blog-2313071898427009436.post-47084150493773649362014-06-12T04:46:00.001-07:002014-06-12T04:54:19.813-07:00Some sld styles.<div dir="ltr" style="text-align: left;" trbidi="on">
<br />
<h1>Empty star with default marks</h1>
<p>For this needed create three point symbolizers with star mark.</p><br>
<pre class="brush:php;">
<PointSymbolizer>
<Graphic>
<Mark>
<WellKnownName>star</WellKnownName>
<Fill>
<CssParameter name="fill">#000000</CssParameter>
</Fill>
</Mark>
<Size>18</Size>
</Graphic>
</PointSymbolizer>
<PointSymbolizer>
<Graphic>
<Mark>
<WellKnownName>star</WellKnownName>
<Fill>
<CssParameter name="fill">#FF0000</CssParameter>
</Fill>
</Mark>
<Size>16</Size>
</Graphic>
</PointSymbolizer>
<PointSymbolizer>
<Graphic>
<Mark>
<WellKnownName>star</WellKnownName>
<Fill>
<CssParameter name="fill">#FFFFFF</CssParameter>
</Fill>
</Mark>
<Size>10</Size>
</Graphic>
</PointSymbolizer>
</pre>
<p>All three point symbolizers pretty same, just difference in size and color. But make sure that you put a smallest makr on the top and biggest on down.<br></p>
<h3>Result:</h3><br>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi20tYluy_1g0ReFyutqUcKPZRbrDXSBWy5a8TuwqISwElHtHkcF-wme2g1gyRoYjEn_wUHLRdgBj1SeO6TMqr7i7LgeywbC6ThEm027b4M7B9WPLZT7wKVbWBBBBOU_xcQ0_lzrlX1LWg/s1600/pir_points.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi20tYluy_1g0ReFyutqUcKPZRbrDXSBWy5a8TuwqISwElHtHkcF-wme2g1gyRoYjEn_wUHLRdgBj1SeO6TMqr7i7LgeywbC6ThEm027b4M7B9WPLZT7wKVbWBBBBOU_xcQ0_lzrlX1LWg/s400/pir_points.jpg" /></a></div>
<h1>Double dashed line</h1>
<p>It's a line dashed with two vertical lines. For this we a needed create three line symbolizers. One with line and two with vertline marks.</p><br>
<pre class="brush:php;">
<LineSymbolizer>
<Stroke>
<CssParameter name="stroke">#00FF00</CssParameter>
</Stroke>
</LineSymbolizer>
<LineSymbolizer>
<Stroke>
<GraphicStroke>
<Graphic>
<Mark>
<WellKnownName>shape://vertline</WellKnownName>
<Stroke>
<CssParameter name="stroke">#00FF00</CssParameter>
<CssParameter name="stroke-width">1</CssParameter>
</Stroke>
</Mark>
<Size>10</Size>
</Graphic>
</GraphicStroke>
<CssParameter name="stroke-dasharray">10 30</CssParameter>
</Stroke>
</LineSymbolizer>
<LineSymbolizer>
<Stroke>
<GraphicStroke>
<Graphic>
<Mark>
<WellKnownName>shape://vertline</WellKnownName>
<Stroke>
<CssParameter name="stroke">#00FF00</CssParameter>
<CssParameter name="stroke-width">1</CssParameter>
</Stroke>
</Mark>
<Size>10</Size>
</Graphic>
</GraphicStroke>
<CssParameter name="stroke-dasharray">10 30</CssParameter>
<CssParameter name="stroke-dashoffset">5</CssParameter>
</Stroke>
</LineSymbolizer>
</pre>
<p>My vertlines is a 1 pixel in width and 10 pixels in lenght. Parameter <b>stroke-dasharray</b> set a distance bitween marks, in my case 30 pixels. Im not sure that clearly know what meen first number 10. Second mark same but with <b>stroke-dashoffset</b>, this paremeter make a offset from the beginning of the line.</p><br>
<h3>Result:</h3>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiWCBLQO0gC4tuWCbBPrjNT0vIbk96TvcfzWT2xxPQSPolsD286c47P0B9jcOg4nYLM9fsaEkL9WQufI4oLdBt7MFeyzft-jpMU-8TdSYl7GsGPyLNLU2hDvRVOopxUCpreMU6qh50kWfc/s1600/pir_lines.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiWCBLQO0gC4tuWCbBPrjNT0vIbk96TvcfzWT2xxPQSPolsD286c47P0B9jcOg4nYLM9fsaEkL9WQufI4oLdBt7MFeyzft-jpMU-8TdSYl7GsGPyLNLU2hDvRVOopxUCpreMU6qh50kWfc/s400/pir_lines.jpg" /></a></div>
</div>
Anonymoushttp://www.blogger.com/profile/12444908737664761341noreply@blogger.com0tag:blogger.com,1999:blog-2313071898427009436.post-4385817533287927502014-04-06T22:40:00.000-07:002014-04-08T21:34:14.312-07:00Simple WMS server using MapServer.<div dir="ltr" style="text-align: left;" trbidi="on">
<h1>WMS Server</h1>
<p>In last time i was instaled a Mapserver+nginx and show a wms layer in browser. Now i want to make a wms server. For this just needed make a correct map file. But before for make sure that MapServer installed correctly run this command in console:</p>
<pre class="brush:php;">
$ ./mapserv -v
</pre>
<p>Output:</p>
<pre class="brush:php;">
MapServer version x.x.x OUTPUT=GIF OUTPUT=PNG OUTPUT=JPEG OUTPUT=WBMP OUTPUT=PDF OUTPUT=SWF OUTPUT=SVG SUPPORTS=PROJ
SUPPORTS=FREETYPE SUPPORTS=WMS_SERVER SUPPORTS=WMS_CLIENT SUPPORTS=WFS_SERVER SUPPORTS=WFS_CLIENT SUPPORTS=WCS_SERVER INPUT=JPEG
INPUT=POSTGIS INPUT=OGR INPUT=GDAL INPUT=SHAPEFILE DEBUG=MSDEBUG
</pre>
<p>If <b>SUPPORTS=WMS_SERVER</b> is here - go ahead.</p>
<h3>1.WMS Server map file:</h3>
<pre class="brush:php;">
MAP
NAME "Simple map"
# Map image size
SIZE 256 256
UNITS METERS
CONFIG PROJ_LIB "/usr/share/proj/" #Path to PROJ lib if needed
SHAPEPATH "/srv/www/maps/shp" #Path to shape files
EXTENT 60.4 56.7 60.7 56.9
#Output projection
PROJECTION
"proj=latlong"
"ellps=WGS84"
"datum=WGS84"
END
# Background color for the map canvas -- change as desired
IMAGECOLOR 255 255 255
IMAGEQUALITY 95
IMAGETYPE png
#Output file format
OUTPUTFORMAT
NAME "png"
EXTENSION "png"
MIMETYPE "image/png"
DRIVER AGG/PNG
IMAGEMODE RGBA
FORMATOPTION "INTERLACE=OFF"
END
# Legend
LEGEND
IMAGECOLOR 255 255 255
STATUS ON
KEYSIZE 18 12
LABEL
TYPE BITMAP
SIZE MEDIUM
COLOR 0 0 89
END
END
WEB
# Set IMAGEPATH to the path where MapServer should
# write its output.
IMAGEPATH '/tmp/'
# Set IMAGEURL to the url that points to IMAGEPATH
# as defined in your web server configuration
IMAGEURL '/tmp/'
# WMS server settings
METADATA
'ows_title' 'Simple map'
ows_onlineresource 'http://MyHost/map/?map=/srv/www/maps/rew.map&'
"wms_srs" "EPSG:4326 EPSG:3857"
"wms_abstract" "atlands demo WMS"
"wms_enable_request" "*"
"wms_encoding" "utf-8"
END
# Template and header/footer settings
TEMPLATE 'fooOnlyForWMSGetFeatureInfo'
END
LAYER
NAME 'test'
TYPE POLYGON
DUMP true
TEMPLATE fooOnlyForWMSGetFeatureInfo
#EXTENT 34.59 49.58 34.63 49.6
DATA my
METADATA
'ows_title' 'test'
wms_srs "EPSG:4326"
END
STATUS OFF
TRANSPARENCY 100
#Layer projection
PROJECTION
"proj=latlong"
"ellps=WGS84"
"datum=WGS84"
END
CLASS
NAME 'test'
STYLE
WIDTH 0.91
OUTLINECOLOR 0 0 0
COLOR 214 205 104
END
END
END
END
</pre>
<p>You can use another projection defenition:</p>
<pre class="brush:php;">
PROJECTION
"init=epsg:4326"
END
</pre>
But i it evoke an error:
<pre class="brush:php;">
msProcessProjection(): Projection library error. no system list, errno: 13
</pre>
For TEMPLATE block using for GetFeatureInfo(). You can find template samples <a href="http://gis-lab.info/other/mapserver-begin-example.zip">here and extract tamplates,symbols,images and fonts folders into map files directory.</a>
<p>You can try generate a map file using a <a href="https://github.com/DMS-Aus/MapManager">MapManager</a>.</p>
<p>Check what we have:</p>
<pre class="brush:php;">
http://MyHost/map/?map=/srv/www/maps/rew.map&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetCapabilitiess
</pre>
<p>In answer you get a xml file with you wms server settings.</p>
<h3>2.Client side</h3>
<p>On client side i have a application useing Leaflet so i just add a new layer:</p>
<pre class="brush:php;">
var wms_server = "http://MyHost/map/?map=/srv/www/maps/rew.map&"
var NewLayer = new L.tileLayer.wms(wms_server, {
layers: 'limite',
format: 'image/png',
transparent: true,
srs:"EPSG:4326"
});
map.addLayer(NewLayer);
</pre>
<p>Used materials:<br/>
1. www.http://gis-lab.info/qa/mapserver-wms.html<br/>
2. www.http://en.it-usenet.org/thread/12216/6154/<br/>
3. www.http://www.cybervox.ru/wiki/Docs/GIS/Mapserver<br/>
4. www.http://profmarcello.blogspot.ru/2013/06/configuracao-de-layers-wms-do-mapserver.html<br/>
</p>
<br /></div>Anonymoushttp://www.blogger.com/profile/12444908737664761341noreply@blogger.com0tag:blogger.com,1999:blog-2313071898427009436.post-20474937761272009282013-11-04T23:43:00.000-08:002013-11-04T23:43:53.508-08:00Ошибка "Библиотека не зарегистрирована" в ИнГео.<div dir="ltr" style="text-align: left;" trbidi="on">
<h1>Решение</h1>
<h3>1.Включить VBScript (команды для 64 битной системы):</h3>
<pre class="brush:php;">
Нажмите кнопку Пуск, выберите пункт выполнить, введите cmdи нажмите кнопку ОК.
Введите %systemroot%\syswow64\regsvr32 %systemroot%\syswow64\vbscript.dllи нажмите клавишу ВВОД.
Введите %systemroot%\syswow64\regsvr32 %systemroot%\syswow64\jscript.dllи нажмите клавишу ВВОД.
Введите %systemroot%\syswow64\regsvr32 %systemroot%\syswow64\dispex.dllи нажмите клавишу ВВОД.
Введите %systemroot%\syswow64\regsvr32 %systemroot%\syswow64\scrobj.dllи нажмите клавишу ВВОД.
Введите %systemroot%\syswow64\regsvr32 %systemroot%\syswow64\scrrun.dllи нажмите клавишу ВВОД.
Введите %systemroot%\syswow64\regsvr32 %systemroot%\syswow64\wshext.dllи нажмите клавишу ВВОД.
Введите %systemroot%\syswow64\regsvr32 %systemroot%\syswow64\wshom.ocxи нажмите клавишу ВВОД.
</pre>
<p>Листинг взят с сайте <a href="http://support.microsoft.com/kb/949140/ru">Майкрософта</a>.<br>
Мне это не помогло.</p>
<h3>2.Запуск ИнГео с правами Администратора:</h3>
<p>Как ни странно это решило проблему.</p>
<br /></div>Anonymoushttp://www.blogger.com/profile/12444908737664761341noreply@blogger.com0tag:blogger.com,1999:blog-2313071898427009436.post-82329754075489202062013-10-02T10:53:00.000-07:002013-10-02T10:53:21.715-07:00Insert Shape file into MS SQL-Server data base.<div dir="ltr" style="text-align: left;" trbidi="on">
It's how to use ogr2ogr to insert Shape file into MS SQL-Server data base.
<pre class="brush:php;">
ogr2ogr -overwrite -f MSSQLSpatial "MSSQL:server=MY-PC-NAME;database=mydatabase;trusted_connection=yes" "D:\data\test_shape.shp"
</pre>
It's create or overwrite table with name - test_shape.
<br /></div>
Anonymoushttp://www.blogger.com/profile/12444908737664761341noreply@blogger.com0tag:blogger.com,1999:blog-2313071898427009436.post-8999740464530685852013-07-18T02:40:00.000-07:002013-08-02T04:33:29.284-07:00Install LifeRay 6.1 on Ubuntu and CentOS<div dir="ltr" style="text-align: left;" trbidi="on">
Today i will install LifeRay 6.1 GA2 on Ubuntu 13.04 with 1Gb memory.<br />
<br />
<b>1. Installing.</b><br />
At first create new user for Liferay:<br />
<br />
<pre class="brush:php;">sudo adduser --home /home/liferay liferay
</pre>
Install Java:<br />
<br />
<pre class="brush:php;">sudo apt-get install default-jre
</pre>
For me it was installed into /usr/lib/jvm/java-7-openjdk-amd64
<br />
On CentOS path was:/usr/lib/jvm/java-1.7.0-openjdk-1.7.0.25.x86_64 <br/>
Get a LifeRay:<br />
<br />
<pre class="brush:php;">http://sourceforge.net/projects/lportal/files/Liferay%20Portal/6.1.1%20GA2/liferay-portal-tomcat-6.1.1-ce-ga2-20120731132656558.zip
unzip liferay-portal-tomcat-6.1.1-ce-ga2-20120731132656558.zip -d /home/liferay
</pre>
Change user to liferay and go to Liferay folder. There i have a problem becouse when i try to start Tomcat it was not work. So all operations i do as administrator.<br />
<br />
<b>2. Tomcat configuration.</b><br />
How we need to set JAVA_HOME variable. And we do it in bash. Go to file /etc/bash.bashrc and add:<br />
<br />
<pre class="brush:php;">JAVA_HOME=/usr/lib/jvm/java-7-openjdk-amd64
export JAVA_HOME
PATH=$PATH:$JAVA_HOME/bin
export PATH
</pre>
For CentOS JAVA_HOME=/usr/lib/jvm/java-1.7.0-openjdk-1.7.0.25.x86_64/jre<br/>
Next you need give a permissions to Tomcat log file. Only heavy artillery helps me:<br />
<br />
<pre class="brush:php;">chmod 777 /home/liferay/liferay-portal-6.1.1-ce-ga2/tomcat-7.0.27/logs/catalina.out
</pre>
Okey, now you can start LifeRay<br />
<br />
<pre class="brush:php;">sh /home/liferay/liferay-portal-6.1.1-ce-ga2/tomcat-7.0.27/bin/startup.sh
</pre>
In console you'll get list of variables. And when in catalina.log appears line<br />
<pre class="brush:php;">INFO: Server startup in 24802 ms</pre>
server is start.<br />
<br />
<b>3. Add Liferay in autoload</b><br />
At first create script /etc/init.d/liferay6<br />
<br />
<pre class="brush:php;">#!/bin/bash
# LifeRay Startup Service script v1.0 by Faraz Haider 6 May 2012
# acts as startup service script for LifeRay Portal.
# USAGE: start|stop|status|logs
#
case "$1" in
start)
echo "Starting LifeRay Web Portal."
export JAVA_HOME=/usr/lib/jvm/java-7-openjdk-amd64
export JRE_HOME=/usr/lib/jvm/java-7-openjdk-amd64/jre
/home/liferay/liferay-portal-6.1.1-ce-ga2/tomcat-7.0.27/bin/startup.sh
;;
stop)
echo "Stopping LifeRay Web Portal."
export JAVA_HOME=/usr/lib/jvm/java-7-openjdk-amd64
export JRE_HOME=/usr/lib/jvm/java-7-openjdk-amd64/jre
/home/liferay/liferay-portal-6.1.1-ce-ga2/tomcat-7.0.27/bin/shutdown.sh
;;
logs)
echo "See the logs of the LifeRay Web Portal."
tail -f /home/liferay/liferay-portal-6.1.1-ce-ga2/tomcat-7.0.27/logs/catalina.out
;;
status)
# Check to see if the process is running
ps aux|grep -i liferay
;;
*)
echo “LifeRay Web Portal Service”
echo $”Usage: $0 {start|stop|status|logs}”
exit 1
esac
exit 0
</pre>
For CentOS:<br />
<br />
<pre class="brush:php;">#!/bin/bash
# chkconfig: 2345 90 10
# description: Liferay Service
# LifeRay Startup Service script v1.0 by Faraz Haider 6 May 2012
# acts as startup service script for LifeRay Portal.
# USAGE: start|stop|status|logs
#
case "$1" in
start)
echo "Starting LifeRay Web Portal."
export JAVA_HOME=/usr/lib/jvm/java-1.7.0-openjdk-1.7.0.25.x86_64/jre
#export JRE_HOME=/usr/lib/jvm/java-7-openjdk-amd64/jre
/home/liferay/liferay-portal-6.1.1-ce-ga2/tomcat-7.0.27/bin/startup.sh
;;
stop)
echo "Stopping LifeRay Web Portal."
export JAVA_HOME=/usr/lib/jvm/java-1.7.0-openjdk-1.7.0.25.x86_64/jre
#export JRE_HOME=/usr/lib/jvm/java-7-openjdk-amd64/jre
/home/liferay/liferay-portal-6.1.1-ce-ga2/tomcat-7.0.27/bin/shutdown.sh
;;
logs)
echo "See the logs of the LifeRay Web Portal."
tail -f /home/liferay/liferay-portal-6.1.1-ce-ga2/tomcat-7.0.27/logs/catalina.out
;;
status)
# Check to see if the process is running
ps aux|grep -i liferay
;;
*)
echo “LifeRay Web Portal Service”
echo $”Usage: $0 {start|stop|status|logs}”
exit 1
esac
exit 0
</pre>
First two comments real important. <br/>
Make file executable:<br />
<br />
<pre class="brush:php;">chmod 755 /etc/init.d/liferay6
update-rc.d tomcat7 defaults
</pre>
For CentOS:<br/>
<pre class="brush:php;">chmod 755 /etc/init.d/liferay6
chkconfig liferay6 on
</pre>
<p>PS: only start,stop and status works<br />
Reboot and be happy.<br></p>
<b>Change Tomcat port</b><br>
<p>Default port is 8080 but in not prety good becouse link www.example.com:8080 looks like a hell. <br>
So go to home/liferay/liferay-portal-6.1.1-ce-ga2/tomcat-7.0.27/conf/server.xml. Find part:<br></p>
<pre class="brush:php;">
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443"
/>
</pre>
And change port 8080 to what you want. I use 80 port for my site address www.example.com.
<br />
<br /></div>
Anonymoushttp://www.blogger.com/profile/12444908737664761341noreply@blogger.com0tag:blogger.com,1999:blog-2313071898427009436.post-44940370847269885522013-07-15T00:58:00.000-07:002014-03-25T22:44:52.668-07:00Install php+FastCGI+nginx on Ubuntu.<div dir="ltr" style="text-align: left;" trbidi="on">
<p>Im continue create my super-amazing-web-GIS-application. I have a weak hardware so i have choice between 2 server side languages php and node.js. With php i can work now and there but for using node.js i have to read tons of books and miles of forums. So i have php i choose you!</p><br>
<b>1. Installing.</b><br>
<p>In previous part we already install nginx and fastCGI. So now we need only php. I will make php+fastCGI not php+php-rgm just becouse im already have fastcgi. If someone will write in comments why i have to use php-rgm i will glad.</p><br>
<p>Install php:</p><br>
<pre class="brush:php;">
apt-get install php5 nginx php5-cgi
</pre>
<p>I was not install mySQL becouse i will use PostgreSQL+PostGIS for spatial data.</p><br>
<b>2. FastCGI configuration.</b><br>
<p>Create file /usr/bin/php-fastcgi and put into:</p><br>
<pre class="brush:php;">
#! /bin/sh
PHP_FCGI_CHILDREN=3
PHP_FCGI_MAX_REQUESTS=1000
exec /usr/bin/php5-cgi
</pre>
<p>Create file /etc/init.d/init-fastcgi and put into:</p><br>
<pre class="brush:php;">
#!/bin/bash
PHP_SCRIPT="/usr/bin/spawn-fcgi -a 127.0.0.1 -p 9000 -u www-data -g www-data -f /usr/bin/php-fastcgi"
RETVAL=0
case "$1" in
start)
$PHP_SCRIPT
RETVAL=$?
;;
stop)
killall -9 php5-cgi
RETVAL=$?
;;
restart)
killall -9 php5-cgi
$PHP_SCRIPT
RETVAL=$?
;;
*)
echo "Usage: sudo /etc/init.d/init-fastcgi {start|stop|restart}"
exit 1
;;
esac
exit $RETVAL
</pre>
<p>Make files executable:</p><br>
<pre class="brush:php;">
chmod 755 /usr/bin/php-fastcgi
chmod 755 /etc/init.d/init-fastcgi
</pre>
<b>3. nginx configuration.</b><br>
<p>You can create new file /etc/nginx/sites-enabled/your-file-name for server configuration:</p><br>
<pre class="brush:php;">
server {
listen 80;
listen [::]:80 default_server ipv6only=on;
root /srv/www/localhost/public_html;
access_log /srv/www/localhost/logs/access.log;
error_log /srv/www/localhost/logs/error.log;
#index index.html index.htm;
# Make site accessible from http://localhost/
server_name localhost;
location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
try_files $uri $uri/ /index.html;
# Uncomment to enable naxsi on this location
# include /etc/nginx/naxsi.rules
}
location /doc/ {
alias /usr/share/doc/;
autoindex on;
allow 127.0.0.1;
allow ::1;
deny all;
}
location ~\.php$ {
root /srv/www/localhost/public_html;
include /etc/nginx/fastcgi_params;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param QUERY_STRING $query_string;
fastcgi_param SCRIPT_FILENAME /srv/www/localhost/public_html$fastcgi_script_name;
}
}
</pre>
<p>But i use default file so i just add:</p><br>
<pre class="brush:php;">
location ~\.php$ {
root /srv/www/localhost/public_html;
include /etc/nginx/fastcgi_params;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param QUERY_STRING $query_string;
fastcgi_param SCRIPT_FILENAME /srv/www/localhost/public_html$fastcgi_script_name;
}
</pre>
<p>into /etc/nginx/sites-enabled/default.</p><br>
<b>4. Site directory.</b><br>
<p>Its all with configurations. Now you can start FastCGI script:</p><br>
<p>Now we need to create directory for our site and log directory:</p><br>
<pre class="brush:php;">
/srv/www/localhost/public_html
/srv/www/localhost/logs
</pre>
<p>In public_html keeped all site content.</p><br>
<b>5. Results.</b><br>
<p>Its all with configurations. Now you can start FastCGI script:</p><br>
<pre class="brush:php;">
sudo /etc/init.d/init-fastcgi start
</pre>
<p>And start nginx:</p><br>
<pre class="brush:php;">
/etc/init.d/nginx start
</pre>
<p>Create file test.php in our site directory with:</p><br>
<pre class="brush:php;">
<?php phpinfo() ?>
</pre>
<p>Go to the localhost/test.php and if you do all right you'll see standart phpinfo() output:</p><br>
<p>Its mean that php+nginx work fine.</p><br>
<p>In my case i get a 404 error becouse nginx tried to find test.php in standart nginx directory /var/www. Restart of nginx and fastcgi not help me, i was forced to reboot machine. But after all work fine.<br>
Another problem was with permissions. So dont forget set to site directory:</p><br>
<pre class="brush:php;">
sudo chmod -R 755 /srv/www/localhost/public_html
</pre>
<b>6. Enable PostgreSQL.</b><br>
<p>Its all nice but i will need PostgreSQL support in php. Now we need to install PostgreSQL module.</p><br>
<pre class="brush:php;">
sudo apt-get install php5-pgsql
</pre>
<p>Restart fastCGI</p><br>
<pre class="brush:php;">
sudo /etc/init.d/init-fastcgi restart
</pre>
<p>And go to localhost/test.php again to make sure that PostgreSQL enabled. You gonna see that part:</p><br>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgo4umKTW9-_8BL_ZVA84_Vk_ti_HBv8C_sy3NLbCXcuF14OcvspnCZyglE0Z4HhPMt_nPtkZvPFXvyeWCzeZfY5QgqrnRVHYa_UVVe-108e4Pf0RrJoqroXY0ipX_1D8qsI9a02pCNWHY/s1600/phpinfo.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgo4umKTW9-_8BL_ZVA84_Vk_ti_HBv8C_sy3NLbCXcuF14OcvspnCZyglE0Z4HhPMt_nPtkZvPFXvyeWCzeZfY5QgqrnRVHYa_UVVe-108e4Pf0RrJoqroXY0ipX_1D8qsI9a02pCNWHY/s1600/phpinfo.jpg" /></a></div>
<p>Its mean all works fine.</p><br>
</div>Anonymoushttp://www.blogger.com/profile/12444908737664761341noreply@blogger.com0tag:blogger.com,1999:blog-2313071898427009436.post-27944767262729579242013-06-26T08:25:00.001-07:002013-06-26T23:31:13.125-07:00MapServer+nginx+FastCGI on Ubuntu.<div dir="ltr" style="text-align: left;" trbidi="on">
Hi.
<p>Im new with Linux. But try to tell how to start with Mapserver on Ubuntu.</p><br>
<b>1. Installing</b><br>
<p>Add UbuntuGis repository:<p><br>
<pre class="brush:php;">sudo add-apt-repository ppa:ubuntugis/ubuntugis-unstable
sudo apt-get update
</pre>
<p>Before install MapServer dont forget that its needed in some libraries: curl, gdal,org, agg. Here more inforamtion about this - <a href="http://mapserver.org/installation/unix.html#introduction">MapServer Site</a></p><br>
<p>Install MapServer, nginx,FastCGI and libgd:</p><br>
<pre class="brush:php;">
sudo apt-get install libgd2-xpm-dev
sudo apt-get install cgi-mapserver mapserver-bin
sudo apt-get install nginx
sudo apt-get install spawn-fcgi
</pre>
<b>2. FastCGI config</b><br>
<p>Create file /etc/init.d/mapserv/ and put into:</p><br>
<pre class="brush:php;">
#! /bin/sh
#
# description: Mapserver Service Manager
# processname: lt-mapserv
# pidfile: /var/run/mapserv.pid
# Source function library.
#. /etc/init.d/functions
# Check that networking is up.
#. /etc/sysconfig/network
if [ "$NETWORKING" = "no" ]
then
exit 0
fi
PREFIX=/usr
NAME=mapserv
PID=/var/run/mapserv.pid
DAEMON=$PREFIX/bin/spawn-fcgi
DAEMON_OPTS=" -a 127.0.0.1 -p 9999 -F 4 -u user -U user -P $PID $PREFIX/lib/cgi-bin/mapserv"
start () {
echo -n $"Starting $NAME "
exec $DAEMON $DAEMON_OPTS >> /dev/null
daemon --pidfile $PID
RETVAL=$?
echo
[ $RETVAL -eq 0 ]
}
stop () {
echo -n $"Stopping $NAME "
killproc -p $PID
#make sure all mapservers are closed
pkill -f lt-mapserv
RETVAL=$?
echo
if [ $RETVAL -eq 0 ] ; then
rm -f $PID
fi
}
restart () {
stop
start
}
# See how we were called.
case "$1" in
start)
start
;;
stop)
stop
;;
status)
status lt-mapserv
RETVAL=$?
;;
restart)
restart
;;
*)
echo $"Usage: $0 {start|stop|status|restart}"
RETVAL=2
;;
esac
exit $RETVAL
</pre>
<p>Make this file executable:<p><br>
<pre class="brush:php;">
chmod +x /etc/init.d/mapserv
</pre>
<b>3. nginx config</b><br>
<p>Create file /etc/nginx/sites-enabled/your-file-name</p><br>
<pre class="brush:php;">
server {
##another server config
listen 80;
server_name your_server.name www.mapserver.your_server.name;
#MapServer
location / {
fastcgi_pass 127.0.0.1:9999;
fastcgi_index mapserv?*;
fastcgi_param SCRIPT_FILENAME /usr/lib/cgi-bin/mapserv$fastcgi_script_name;
include fastcgi_params;
}
}
</pre>
<p>I was make all thing on localhost. So i not create new file, but just add lines with:</p><br>
<pre class="brush:php;">
location /map/ {
fastcgi_pass 127.0.0.1:9999;
fastcgi_index mapserv?*;
fastcgi_param SCRIPT_FILENAME /usr/lib/cgi-bin/mapserv$fastcgi_script_name;
include fastcgi_params;
}
</pre>
into /etc/nginx/sites-enabled/default.
<p>Its all with configurations. Now you can start FastCGI script:</p><br>
<pre class="brush:php;">
service mapserv start
</pre>
And start nginx:
<pre class="brush:php;">
/etc/init.d/nginx start
</pre>
<p>Go to the localhost/map/ and if you do all right you'll see:</p><br>
<pre class="brush:php;">
No query information to decode. QUERY_STRING is set, but empty.
</pre>
<p>Its mean that MapServer+nginx work fine.</p><br>
<b>4. Create map.</b><br>
<p>Now lets do your first map.For this we need some data. I take Shape files: http://gis-lab.info/other/mapserver-begin-example.zip. Extract it everywhere you want, i do it into /home/my-user/example.</p><br>
<p>MapServer have no admin panel like Geoserver. For make map you gonna create *.map files. In zip already contain some. We'll use file polt.map:</p><br>
<pre class="brush:php;">
# Аннотированный map-файл (за основу взят файл из учебника
# http://biometry.gis.umn.edu/tutorial/)
#
# Все, что идет за символом решетки - комментарий и программой не обрабатывается
#
# Map-файлы начинаются с ключевого слова MAP, обозначающего начало
# "map"-объекта. Закрывает map-объект ключевое слово END в конце файла. Вся
# карта, которая будет отображаться пользователю описывается внутри.
MAP
IMAGETYPE GIF
EXTENT 34.59 49.58 34.63 49.6
SIZE 400 300
SHAPEPATH "/home/user/example/shp/"
IMAGECOLOR 255 255 255
# Внутри MAP-объекта определяются новые объекты - слои (LAYER).
# Обязательно нужно определить по крайней мере один слой.
# Количество слоев ограничено сверху (по умолчанию - не больше 100 слоев),
# если нужно большее количество слоев, придется перекомпилировать
# MapServer (см. map.h)
LAYER # Определяем полигональный слой
NAME veget
DATA Poltava10_Vegetation_region
STATUS ON
TYPE POLYGON
# Внутри слоя нужно определить как минимум один класс. Классов может быть
# несколько, но не больше 10 (иначе опять придется перекомпилировать MapServer)
CLASS
NAME "Растительность"
# Внутри класса определяются стили: как именно данный класс отобразить
# на карте.
STYLE
COLOR 232 232 232
OUTLINECOLOR 32 32 32
END
END
END # Конец определения слоя
END # Конец определения карты
</pre>
<p>There much comments on russian, but don't worry this files works fine. This map contains only one layer veget There you gonna change only SHAPEPATH parameter if you extract your zip archive in another place.</p><br>
<p>For see this map add in your address line:</p><br>
<pre class="brush:php;">
http://localhost/map/?map=/home/user/example/polt.map&layer=veget&mode=map
</pre>
<p>If you see map image:</p><br>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEibuLD2BFI5IWtgvqe4IHDzc5g5UvsUdelco-vUPZ0JC_QxrPHbgo0mT-IyTn4sxrPDbdW2wAuWMojohEO322dw5UpOAtPpI50wkP0bgkxnzzWY2gxJMtvgv7r64cxhAkCn5aylrk_pqB4/s1600/mapserver-begin-01.gif" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEibuLD2BFI5IWtgvqe4IHDzc5g5UvsUdelco-vUPZ0JC_QxrPHbgo0mT-IyTn4sxrPDbdW2wAuWMojohEO322dw5UpOAtPpI50wkP0bgkxnzzWY2gxJMtvgv7r64cxhAkCn5aylrk_pqB4/s1600/mapserver-begin-01.gif" /></a></div>
<p>Its mean all works fine.</p><br>
<p>Thanks for <a href="https://github.com/yodeski">Yodeski Rodríguez Álvarez</a> for nginx and FasrCGI configuration files. Part with map creating takes from <a href="http://gis-lab.info/qa/mapserver-begin.html">gis-lab.ru</a></p>
</div>
Anonymoushttp://www.blogger.com/profile/12444908737664761341noreply@blogger.com3