How to get a feature collection from current selection in MapInfo MapXtreme

If you are looking for answers to the below questions ?

How to get a feature collection from current selection in MapXtreme ?
How to get a feature collection using a select region tool in MapXtreme ?
How to get a feature collection of all the selected regions in MapXteme ?

If yes I have an answers for you,
1. First select a layer as Feature Layer, this layer will be the layer where you will be searching for the selected regions.
2. Now, Using Session.Current.Selection.DefaultSelection() pass the table of the currently selected layer as shown in the code below.
3. The above used method will return a IResultSetFeatureCollection irfc, here you will get a collection of all the selected region of that layer.
Below is the code that does the same.

C# code
FeatureLayer lyr=mapControl1.Map.Layers["layerNameToGoHere"] as FeatureLayer ;
IResultSetFeatureCollection irfc = Session.Current.Selections.DefaultSelection[lyr.Table ];
 
VB.NET Code
Dim lyr as FeatureLayer =mapControl1.Map.Layers["layerNameToGoHere"]
Dim irfc as IResultSetFeatureCollection = Session.Current.Selections.DefaultSelection

How to write Special characters in a file using vb.net

You may need to read / write some special symbols like these æ,Ø,å etc, into a text file. I had a similar situation where I needed to write some danish characters into the file.
Below is what I had used.
Dim encoding As Encoding
encoding = New UTF8Encoding()

Dim sw As StreamWriter
sw = New StreamWriter("filename.txt", False, encoding)
sw.WriteLine("vaøøibhav")
sw.WriteLine("vøøøøvvs")
sw.Close()
 
And if all fails, try this
Dim sw As New StreamWriter("filename.txt", False, System.Text.Encoding.Default)

How to save current map window image in your had drive

In this tutorial i will show you that how can we save  the current map window image to your hard drive.

private void button1_Click (object sender, EventArgs e)
{
MapInfo.Mapping.MapExport exportObject = new MapInfo.Mapping.MapExport (this.mapControl1.Map.Clone () as MapInfo.Mapping.Map);
exportObject.ExportSize = new MapInfo.Mapping.ExportSize (this.mapControl1.Map.Size.Width, this.mapControl1.Map.Size.Height);
exportObject.Format = MapInfo.Mapping.ExportFormat.Bmp;  / / Save to the clipboard
System.Windows.Forms.Clipboard.SetDataObject (exportObject.Export ()); / / Save to your hard drive
exportObject.Export (@ "D: \ Image.bmp");
MessageBox.Show ("Save successful!");
}

How to decide visibility of the layers using check boxes

In this small tutorial i will show you that how can we decide visibility of the layers depending on check boxes in MapInfo

  
code is very simple as shown bellow.

   private void checkBox1_CheckedChanged (object sender, EventArgs e)
         {
             this.mapControl1.Map.Layers [checkBox1.Text.ToString ()]. ​​Enabled = checkBox1.Checked;
         }

How to make a layer selectable or not selectable in MapInfo MapXtreme

In this tutorial i will show you that how can we make a layer selectable  or not selectable

/ / All the layers are not optional
                 MapInfo.Mapping.LayerHelper.SetSelectable (item, false);
   / / A layer is not optional
             foreach (MapInfo.Mapping.IMapLayer layer in mapControl1.Map.Layers)
             {
                 if (object.ReferenceEquals (layer, mapControl1.Map.Layers ["GZ_River_LL"]))
                 {
                     MapInfo.Mapping.LayerHelper.SetSelectable (layer, false);
                 }
         }

How to obtain current mouse co ordinates in MapInfo MapXtreme

Here i will show you that how can we get the current mouse co ordinates in the MapInfo MapXtreme

private void mapControl1_MouseMove (object sender, MouseEventArgs e)
         {
             System.Drawing.PointF DisplayPoint = new PointF (eX, eY); / / create two-dimensional midpoint of x and y coordinates of the ordered pair
             MapInfo.Geometry.DPoint MapPoint = new MapInfo.Geometry.DPoint (); // create a point layer
             MapInfo.Geometry.DisplayTransform converter =
              this.mapControl1.Map.DisplayTransform; converter.FromDisplay (DisplayPoint, out MapPoint); / / display coordinates of a point into the map coordinates of the point or layer
             this.statusBar1.Text = "Cursor Location:" + MapPoint.x.ToString () + "," + MapPoint.y.ToString ();
         }

 
Explanation:

DisplayTransform.FromDisplay method (Rectangle, DRect)
Will display the coordinates of the rectangle into a map or a layer of rectangular coordinates.
public void FromDisplay (
Rectangle srcRect,out DRect destRect)
Rectangle srcRect :  display coordinates of the rectangle.
out DRect destRect : map or a layer of rectangular coordinates.



DisplayTransform.ToDisplay method (DPoint, Point) Point of the map or layer into a display point.
public void ToDisplay (
DPoint pntSrc,out Point pntDest )
DPoint pntSrc : maps or layers points out Point pntDest  : display points.

Solving Unable to update the EntitySet 'TestInstanceName' because it has a DefiningQuery and no element exists in the element to support the current operation. Problem


Hello,

If you get this error while working with entity framework ...

"Unable to update the EntitySet 'TestInstanceName' because it has a DefiningQuery and no <DeleteFunction> element exists in the <ModificationFunctionMapping> element to support the current operation."

then there is only one thing that you are missing is "Primary Key" in database table  or you are not passing primary key value while updating your data.

how to bind the dropdown list with Webgrid in ASP.NET MVC3, Razor

In this tutorial i will show you that how can we create the dynamic webgrid on dropdown selected index change in MVC & razor using JSON ....



What we will do is that on dropdown change event we will call the jquery which will take the value of the selected item of dropdown list & will pass it to Action....


DropDown list is ...

@Html.DropDownListFor
(model => @Model.ListId, new SelectList(Model.Lists, "ListId""Name"), "--Select a list--")



also we have to one empty Div like this...
<div id="grid">   </div>

Jquery is ....

    <script type="text/javascript">
        $(function() {
            $('#ListId').change(function() {
                var customDataListId = $("#ListId").val();
     $.getJSON('@Url.Action("Data")', { id: ListId}, function (result) {
                    var customDataList = $('#grid');
                    customDataList.empty();
                    customDataList.append(result.Data);
                });
            });
        });
    </script>
 
Where....  "#ListId" is Name property of the Dropdown list...
     ......    "Data" is action name 
     .....    "result" is result returned from the action .....  see bellow for action method
      .......   "#grid" is id of the empty grid

Now We will write ActionMethod....
 
[AcceptVerbs(HttpVerbs.Get)] 
        public JsonResult CustomData(int id)
        {
            // here I get the data from the database in result
            var result = _customDataListRepository.GetCustomDataWithId(id).ToList(); 
 
//now I create the new webgrid ,also i will pass result as it parameter
            var grid = new WebGrid(result);
 
//now i create the columns of the grid ....
var htmlString = grid.GetHtml
(tableStyle: "paramTable", htmlAttributes: new {id = "grid"},
                                          columns: grid.Columns(
                                              grid.Column("Name""MyName"),
                                              grid.Column("CustomValue""MyCustomValue")
                                              ));
// while returning i am passing this grid as htmlstring...
            return Json(new
                            {
                                Data = htmlString.ToHtmlString()
                            }
                , JsonRequestBehavior.AllowGet);
        } 

By doing this .... every time new grid will be created & old grid will be deleted .....
 
Also if you want to show whole table which u get from the database  then....
[AcceptVerbs(HttpVerbs.Get)] 
        public JsonResult CustomData(int id)
        {
            // here I get the data from the database in result
            var result = _customDataListRepository.GetCustomDataWithId(id).ToList();   
//now I create the new webgrid ,also i will pass result as it parameter
            var grid = new WebGrid(result); //now i create the columns of the grid ....
var htmlString = grid.GetHtml();// while returning i am passing this grid as htmlstring...
            return Json(new
                            {
                                Data = htmlString.ToHtmlString()
                            }
                , JsonRequestBehavior.AllowGet);
        }
 
 
Like this we can create dynamic webgrid using JSON with dropdown list 

How to change color or background of the menu tab of current page using css & jquery

Hello,
In this tutorial i will show you that how can we change the color or background of the menu tab when we are on that page.
<div class="menu">
            <ul>
                <li><a href="/Home">Home</a></li>
                <li><a href="/About Me">Forms</a></li>
                <li><a href="/Contact Me">Look &amp; Feel</a></li>
                <li><a href="/Blog">Security</a></li>
            </ul>
        </div>
 
 The css is somthing like this....
 
.menu ul{
    width100%;
    height21px;
    list-stylenone;
    margin0px;
    padding0px 0px 0px 3px;
}
  .menu ul li {
    displayblock;
    floatleft;
    text-aligncenter;
    margin-left3px;
    margin-right3px;
    border-radius5px 5px 0px 0px;
    -moz-border-radius5px 5px 0px 0px;
    -webkit-border-radius5px 5px 0px 0px;
    border-left1px solid black;
    border-right1px solid black;
    border-top : 1px solid black;
    background-color#ececec;
}  
 
 
 .menu ul li a{
    text-decorationnone;
    width90%;
    colorblack;
    padding-left29px;
    padding-right29px;
    
 } 
 
  .menu ul li a:hover{
     colorblue;
     text-decorationunderline;
 } 
 
 .menu ul li.active a{
    border-bottom2px solid white;
    background-colorwhite;
}
 
 
and a samll jquery which does all magic is ...
<script>
        $(".menu ul li").removeClass("active");
        $(function () {
            var url = window.location.pathname;  
            var activePage = url.substring(url.lastIndexOf('/') + 1);
            $('.menu ul li a').each(function () {
       var currentPage = this.href.substring(this.href.lastIndexOf('/') + 1);
             if (activePage == currentPage) {
               $(this).parent().addClass('active');
                }
            });
        });
</script>
 
  

How to save a .GST geoset file using MapInfo

It is possible to save a map in .gst form using the WorkSpacePersistence class.

1. Firstly you will need to create an object of FileStream class.

2. The First argument in the constructor of the FileStream class is the file path i.e path where this file needs to be saved.

3. Second argument is the FileMode, I have used FileMode.Create. There are various other option when using FileStream, refer this link same.

4. Use the save method from the WorkSpacePersistance class, pass the map and stream as arguments.

(Note : myMap is the name of the MapControl I have used in my application)

Dim stream As Stream
stream = New FileStream("D:/vaibhav/mumbai.gst", FileMode.Create)

Dim wsp As New MapInfo.Persistence.WorkSpacePersistence()
wsp.Save(myMap.Map, stream)

Format Date Time using BoundColumn / ButtonColumn in DataGrid

A very common desire is to set a column of a DataGrid/GridView to display just the month, day and year (or other custom formats) for a dateTime field.

Below is an example for the same,

The first column with header 'DateTime 1' is a BoundColumn which uses DataFormatString="{0:yyyy.MM.dd}". This will format a date time string of 28-10-2011 12:52:00 to 2011.10.28.

The same can be used with ButtonColumn, as shown here the date time string of 28-10-2011 12:52:00 is converted to a format of 2011.10.28 12:52

<asp:DataGrid ID="abc" CssClass="default" DataKeyField="Id"  
OnItemCommand="myCommand" AutoGenerateColumns="false" Runat="Server" > 

<Columns> 

<asp:BoundColumn HeaderText="DateTime 1" DataField="dt1"  
DataFormatString="{0:yyyy.MM.dd}"  /> 

<asp:ButtonColumn HeaderText="DateTime 2" 
 DataTextField="dt2" DataTextFormatString="{0:yyyy.MM.dd hh:mm}"  
ButtonType="LinkButton" CommandName="Select" runat="server"/> 

</Columns> 

</asp:DataGrid>

How to show image from binary data in database in MVC3 razor?

In this tutorial i will explain that how can we show image in web page from binary data of database.

Get image from database in your controller....
        public ActionResult GetImage(int id)
         {
            var imageData = ....get image from database in binary formate...
            return File( imageData, "image/jpg" );
         }
                Create the action in your controller which will get the binary data of the image from database in the variable.
                Return the File to the view with binary data & image file type.


Call the action from the view
<img src="@Url.Action("GetImage""ImageLoader"
new { id = @Model.Id })" name="logoFile"/>

                Now we need to call the action from the view. Which can be done as shown above.
Where :
GetImage : Action Name. (here put your action name)
ImageLoader : Controller Name. (here put your controller name)
@Model.Id : id of the data for which you want to show the image (here put id for which you want to show the image )


razor examples & work sheet for asp.net MVC

HtmlHelper
Method
Action
Output
@Html.ActionLink(s:text, s:action, o:attributes)
Writes an anchor tag to a link for a specific action.
<a href="action">text</a>
@Html.AntiForgeryToken(s:salt, s:domain, s:path)
Generates a hidden form field (anti-forgery token) that is validated when the form is submitted.

@Html.AttributeEncode(s: input)
HTML-encodes the string (as an attribute).

@Html.BeginForm(s:action, s:controller, o:values)
Writes an opening <form> tag to the response.
<form action="/controller/action/">
@Html.BeginRouteForm(s:routeName)
Writes an opening <form> tag for the route.
<form action="route">
@Html.CheckBox(s:name, b:checked)
Returns a check box input element.
<input type="checkbox" name="name" id="name" checked="checked" />
@Html.CheckBoxFor(e:expression)
Returns a check box input element for the model.
<input type="checkbox" name="name" id="name" checked="checked" />
@Html.DropDownList(s:name, list:selectlistitems)
Returns a single-selection select element.
<select name="name" id="name"></select>
@Html.DropDownListFor(e:expression, list:selectlistitems)
Returns a single-selection select element for the model.
<select name="name" id="name"></select>
@Html.Encode(s:input)
HTML-encodes the string.

@Html.EndForm()
Renders the closing </form> tag to the response.
</form>
@Html.Hidden(s:name, o:value)
Returns a hidden input element.
<input type="hidden" value="value" name="name" />
@Html.HiddenFor(e:expression)
Returns a hidden input element for the model.
<input type="hidden" value="value" name="name" />
@Html.ListBox(s:name, list:selectlistitems)
Returns a multi-select select element.
<select multiple="multiple" name="name" id="name"></select>
@Html.ListBoxFor(e:expression, list:selectlistitems)
Returns a multi-select select element for the model.
<select multiple="multiple" name="name" id="name"></select>
@Html.Password(s:name, o:value)
Returns a password input element.
<input type="password" value="value" name="name" />
@Html.PasswordFor(e:expression)
Returns a password input element for the model.
<input type="password" value="value" name="name" />
@Html.RadioButton(s:name, o:value, b:checked)
Returns a radio button input element.
<input type="radio" value="value" name="name" checked="checked" />
@Html.RadioButtonFor(e:expression, o:value)
Returns a radio button input element for the model.
<input type="radio" value="value" name="name" checked="checked" />
@Html.Partial(s:name, o:model)
Renders a partial view (.cshtml).

@Html.RouteLink(s:text, s:routeName)
Returns an anchor element (a element) that contains the virtual path of the specified action.
<a href="action">text</a>
@Html.TextArea(s:name, s:value)
Returns the specified textarea element.
<textarea name="name">value</textarea>
@Html.TextAreaFor(e:expression)
Returns the specified textarea element for the model.
<textarea name="name">value</textarea>
@Html.TextBox(s:name, o:value)
Returns a text input element.
<input type="text" name="name" value="value" />
@Html.TextBoxFor(e:expression)
Returns a text input element for the model.
<input type="text" name="name" value="value" />
@Html.TextBoxFor(e:expression)
Returns a text input element for the model.
<input type="text" name="name" value="value" />


UrlHelper
Method
Action
Output
@Html.Action(s:action, s:controller)
Generates a fully qualified URL to an action method.

@Html.Content(s:path)
Converts a virtual (relative) path to an application absolute path.

@Html.Encode(s:url)
Encodes special characters in a URL string into character-entity equivalents.

@Html.RouteUrl(s:route)
Generates a fully qualified URL for the specified route name.


JQuery Introduction & JQuery Search Characters



We mainly use J Query for searching for some items on the page & doing something with them .

The JQuery functions which finds the items on the page are called selectors.

Base Selector in J Query is JQuery() or $() function.

String arguments can be passed to this functions in three ways 
 
Select by Element: This finds the elements with specific tag name & returns the array of that.
E.g.: $(“h2”) – this will find all <h2> tags.

Select by ID: This finds the elements which has the specified ID. We use “#” character to find the ID.
E.g.: 1) $(“#div1”) ---then this will search the elements which have the ID=div1.  
         2) If you want to search the element <div ID=”mydiv”> then JQuery would be $(“#mydiv”).

Select by CSS: this finds the elements with specific CSS class names. We use “.” to find the CSS class.
E.g.: 1) $(“.divStyle”) ---then it will search for the element which has CSS class as divStyle.
         2) If we want to search for the element <div class=”myDiv”> then JQuery will be $(“.myDiv”).

1.
There are some search characters used in JQuery to find the specific elements.

1.       “*” (asterisk) character: This is used to search the specified search term in the elements.
E.g.: $(“a[href*=net]”) ---- this will search in all <a> tags which has the text “net” as the part of the href attribute.

2.       “^” (caret) character: This is used to search the specified search term at the starting of the string.
E.g. $(“a[href^=folder/]”) ---- This will search in all <a> tags which has the text “folder/” at the beginning of the href attribute.

3.       “$” (dollar) character: This is used to search the specified search term at the end of the string. 
      E.g. $(“a[href$=in]”) ---- This will search for all <a> tags which has the text “in” at the end of the href      attribute.

4.       “!” (exclamation) character: This is used to search the elements whose attributes do not match the specified string 
      E.g.: $(“a[href!==http://www.google.com]”) ---- This will search for all <a> tags whose href attribute is not equal to www.google.com