Get rid of Tinychat advertisement and other useless crap


in yr browser get to Developer console “Press F12” , or some other way if u have a diff browser.

 

all modern browser have dat Dev console, once u see it, copy and paste this script

$(‘#right_block’).remove();$(‘#share-bar’).remove();$(‘#room_header’).remove();$(‘#header’).remove();$(‘#footer’).remove();

 

and press enter

 

Posted in C# | Leave a comment

Open or expand dropdown with javascript


 

tiny code to open a dropdown by code

            window.openDropdown = function (str) {
                var dropdown = document.getElementById('myDropDown');
                var event;
                event = document.createEvent('MouseEvents');
                event.initMouseEvent('mousedown', true, true, window);
                dropdown.dispatchEvent(event);
            }

and then use this to fire the event

openDropdown(0);

Posted in C# | Leave a comment

Horizontal Scroll any element with images or items inside of it


 

here a simple function to scroll an element with items it for example images, just give the function the element, then 1 callback for the scroll up event, and another callback for the scroll down event. feel free to update/extend this snippet.

 

 

        <script>

            var horizontalScroller = function(elm, callbackScrollUp, callbackScrollDown) {
                // detect available wheel event
                var supports = "onwheel" in document.createElement("div") ? "wheel" :   // Modern browsers support "wheel"
                    document.onmousewheel !== undefined ? "mousewheel" :                // Webkit and IE support at least "mousewheel"
                    "DOMMouseScroll";                                                   // let's assume that remaining browsers are older Firefox

                $(elm).bind('DOMMouseScroll mousewheel wheel', function(e) {
                    var direction = 0;
                    var flip = false;

                    switch (supports) {
                        case "mousewheel": // IE, and for safari the values are reversed here
                            direction = e.originalEvent.deltaY;
                            if (direction === undefined) {
                                direction = e.originalEvent.wheelDeltaY;
                                flip = true;
                            }

                            if (direction >= 0) {
                                (flip === true) ? callbackScrollUp(e) : callbackScrollDown(e);
                            } else {
                                (flip === true) ? callbackScrollDown(e) : callbackScrollUp(e);
                            }
                        break;
                        case "wheel": // FF, Chrome
                            direction = e.originalEvent.wheelDelta;;

                            if (direction === undefined) {
                                direction = e.originalEvent.deltaY;
                                flip = true;
                            }

                            if (direction >= 0) {
                                (flip === true) ? callbackScrollDown(e) : callbackScrollUp(e);
                            } else {
                                (flip === true) ? callbackScrollUp(e) : callbackScrollDown(e);
                            }
                        break;
                    default:
                        alert("other scroll type");
                        break;
                    }
                    console.log(flip);
                    e.preventDefault();
                });
            }

            var scrollUp = function(e) {
                console.log("scrolling up");
            }

            var scrollDown = function(e){
                console.log("scrolling down");
            }

            horizontalScroller(".row", scrollUp, scrollDown);
        </script>
Posted in JQuery | Tagged , , , , , | Leave a comment

Detect up or down scroll event in jquery


 

Here is a little snippet on how to detect the scroll event going up or down

        <script>
            $(".myDiv").bind('mousewheel', function(e) {
                if (e.originalEvent.wheelDelta >= 0) {
                    console.log('Scroll up');
                }
                else {
                    console.log('Scroll down');
                }
                e.preventDefault();
            });
        </script>
Posted in C# | Leave a comment

Best Practices For Branching with teams


Source Control

Branch for Team. You branch to isolate sub-teams so they can work without being subject to breaking changes, or can work in parallel towards unique milestones.

Development is branched from Main and used to isolate active development. Development branches may be temporary, in order to develop risky changes without impacting Main.

Main contains your main source tree. Changes from other branches are integrated here.

Releases contains branches you have already shipped but now need to maintain for customers. This provides isolation from the active development occurring in your development branch. It also contains a current release branch which is branched from Main and contains the version you are currently locking down prior to release. You work in this branch to prepare your software for release, while others continue to work in the Development branch working on new features.

Branch for Team

There might be a one-to-one correspondence between team and feature, but in some cases a team might work on multiple features. 

The following is a physical view showing branching for sub-team development:

My Team Project

└ Development → Isolated development branch container

│     └ Team 1 → Team branch

│     │     └ Feature A → Isolated branch for development

│     │     │         └ Source

│     │     └ Feature B → Isolated branch for development

│     │                └ Source

│     │

│     └ Team 2 → Team branch

│            └ Feature A → Isolated branch for development

│            │          └ Source

│            └ Feature B → Isolated branch for development

│                    └ Source

└ Main → Main Integration branch

        └ Source

Rationalize your branch/merge strategy with the frequency with which you want to produce builds. A deeper branching structure results in more time to merge from child branches to the main integration branch. 

Symptoms of this causing a problem for your development team include:

Broken builds where the fix takes too long to propagate up to the main integration branch.

Missed milestones because features take too long to propagate up to the main branch.

Large amounts of time are spent merging changes between various branches.

If this becomes a problem for your team, consider reducing the depth of your branching structure.

The following is an example of a complex branching structure:

My Team Project

└ Development – Container to isolate active development branches

│     └ Feature A – Isolated branch for development

│     │     └ Source

│     └ Feature B – Isolated branch for development

│             └ Source

└ Main – Main integration and build branch. All changes come together here.

│     └ Source

│     └ Other Asset Folders

└ Releases – Container for current release and maintenance branches

│     └ Release 2– Active maintenance branch

│     │      └ Source

│     │      └ Other Asset Folders

│     └ Release 3 – Active maintenance branch

│     │      └ Source

│     │      └ Other Asset Folders

│     └ Release 4 – Branch containing the code currently being locked down to release

│             └ Source

│             └ Other Asset Folders

└ Safe Keeping

       └ Release 1 – Old release in safe keeping

└ Source

               └ Other Asset Folders

This structure includes:

Feature branches for multiple teams to work in isolation.

A main branch to gather changes by all teams as well as bug fixes from the release branches.

A release branch used to lockdown the current release.

A maintenance branch for an old release that is being actively maintained and supported.

Safekeeping branches for older releases that are no longer being maintained.

Do not branch unless your development team needs to work on the same set of files concurrently. If you are unsure about this, you can label a build and create a branch from that build at a later point. Merging branches can be time consuming and complex, especially if there are significant changes between them.

Do not branch too deeply. Because it takes time to execute each merge and resolve conflicts, a deep branching structure can mean that changes in a child branch may take a very long time to propagate to the main branch. This can negatively impact project schedules and increase the time to fix bugs.

Summary

Branches are usually created to lock down a release, to maintain a previous release, or to support isolated parallel development. You should not branch unless you have good reason to do so.

When creating branches, you should logically structure your branch trees so that you only need to merge along the hierarchy (up and down the branch tree) rather than across the hierarchy. Merging across the hierarchy is time-consuming and error-prone.

For large teams, the branching structure is deeper, so you should be prepared for more lag time between a change occurring in a development branch and that change being merged back into the main integration branch.

http://msdn.microsoft.com/en-us/library/bb668955.aspx

clip_image001

Posted in Source Control | Tagged , , , , , , | 1 Comment

System.Data.SqlClient.SqlException: Incorrect syntax near ‘<‘. MindScapeLightSpeed Entity


 

When adding a 2e partial class for a lightspeed partial entity  class just to add extra properties i ran into this error

System.Data.SqlClient.SqlException: Incorrect syntax near '<'.

and my 2e partial class looked like this

    public partial class HotelTheme
    {
        public Theme Theme { get; set; }

        public string ThemeName { get; set; }
    }

and i only wanted to add a simple property called ThemeName, then i thought i should maybe try to make a public variable out of it like this.

    public partial class HotelTheme
    {
        public Theme Theme { get; set; }

        public string ThemeName;
    }

but then i got the error

System.Data.SqlClient.SqlException: Invalid column name 'ThemeName'.

By now i was thinking Wtf! but i did not give up.

and here is the solution to add your own properties into the 2e partial class

    public partial class HotelTheme
    {
        public Theme Theme { get; set; }

        [Transient]
        private string _themeName;
        public string ThemeName
        {
            get { return _themeName; }
            set { _themeName = value; }
        }
    }

you cannot use an automatic property, you must use the old skool way, and add the attribute Transient to yr private variable.

Use partial classes to add behaviour to generated entity classes. You can also add properties in partial classes, but if those properties introduce additional state (as opposed to being wrapper or adapter properties around the existing LightSpeed fields), be sure to mark the backing fields with the TransientAttribute so LightSpeed doesn’t try to persist them.

Never use automatic properties in a LightSpeed entity class – the C# compiler generates a backing field which doesn’t map to a database column, and you can’t get at the field to mark it transient.

Hope this helps you out to ; )

Greets JB

Posted in C#, Mindscape Lightspeed | Tagged , , , , , , | Leave a comment

404 Web Api Controller Path / Route not found in .Net Website


 

When adding a Api 2.0 controller to your web forms project on staging or a local server all might work fine, but when moving it to a production server you might get the error that your api controller path/route could not be found and your page will throw a 404.

There was a solution that mentioned that you could add the following code (Dont! use the following on a production, unless you know what it does)

<system.webServer>
    .....
    <modules runAllManagedModulesForAllRequests="true" />
    .....
</system.webServer>

but that is not the real solution cause it might end up not loading all files needed for your website, in my case scripts and and css files could not be loaded, unless i was logged in, but that is not an option for me.

to have the real fix add this in your web.config

    <system.webServer>
        <modules>
            <remove name="UrlRoutingModule-4.0" />
            <add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="" /> 
        </modules>
    </system.webServer>

so in my web.config the system.webserver section looks like this

<system.webServer> 
    <handlers>
        <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
        <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
        <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
        <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
        <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
        <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
    <modules>
        <remove name="UrlRoutingModule-4.0" />
        <add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="" />
    </modules>
</system.webServer>

 

Hope this helps you out as it helped me out getting my Api controller to work on a production server

Greets JB

Posted in Api Controllers 2.0, C# | Tagged , , , , , | Leave a comment

Add Web Api controller 2.0 to old asp.net website project


To add an Web Api 2.0 controller to your old asp.net forms website project do the following steps

First right click on yr website, and select add new item, and choose “Web Api Controller Class” and name it for example “MyApiController” and place it in the “App_Code folder”

image

Once you have created the api controller, remove all the methods that are placed in the api controller by default and add this method for testing

using System;
using System.Web.Http;

public class MyApiController : ApiController
{
    [HttpGet]
    public MyApiResult GetHelloWorld()
    {

         return new MyApiResult { Data = “JohnnyBlade”, Date = DateTime.Now};
    }
}

Also create a new class called “MyApiResult” in the “App_code” folder and add the following properties

using System;
public class MyApiResult
{
    public string Data { get; set; }
    public DateTime Date { get; set; }
}

Then go to your “Global.asax” file and go to the method “Application_Start” and add the following code and namespaces

<%@ Application Language=”C#” %>
<%@ Import namespace=”System.Web.Http”  %>
<%@ Import Namespace=”System.Web.Routing” %>
<%@ Import Namespace=”System.Net.Http.Formatting” %>
<%@ Import Namespace=”Newtonsoft.Json” %>
<%@ Import Namespace=”Newtonsoft.Json.Serialization” %>

<script runat=”server”>

void Application_Start(object sender, EventArgs e)
{
    // set the route for the api
    RouteTable.Routes.MapHttpRoute(
        “DefaultApi”,
        “api/{controller}/{action}/{id}”,
        new { id = System.Web.Http.RouteParameter.Optional }
    );
    // set the configuration
    GlobalConfiguration.Configuration.Formatters.Clear();
    GlobalConfiguration.Configuration.Formatters.Add(new JsonMediaTypeFormatter
    {
        SerializerSettings = new JsonSerializerSettings
        {
            Formatting = Formatting.None,
            DateFormatHandling = DateFormatHandling.IsoDateFormat,
            NullValueHandling = NullValueHandling.Include,
            ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
            ContractResolver = new CamelCasePropertyNamesContractResolver(),
        }
    });
}

</script>

the RouteTable makes sure that you can access/find your ApiController by a custom route prefixed with “Api”

    RouteTable.Routes.MapHttpRoute(
        “DefaultApi”,
        “api/{controller}/{action}/{id}”,
        new { id = System.Web.Http.RouteParameter.Optional }
    );

for example: http://localhost:12345/api/MyApi/GetHelloWorld

 

the GlobalConfiguration.Configuration.Formatters adds a new formatter for the Json result if you don’t add this, then yr result will be a Json result that is also in XML tags or only pure XML, and that’s what you don’t want, unless yr happy with that.

<MyApiResult xmlns:i=”http://www.w3.org/2001/XMLSchema-instance&#8221; xmlns=”http://schemas.datacontract.org/2004/07/”><Data>JohnnyBlade</Data><Date>2014-11-26T09:24:06.7804627+01:00</Date></MyApiResult&gt;

and if you use the formatter and SerializerSettings the result will be 🙂 and that’s what i need

{"data":"JohnnyBlade","date":"2014-11-26T09:03:45.581355+01:00"}

 

This should get you started to customize this further

Greets JB

Posted in Api Controllers 2.0 | Tagged , , , , , , , , | Leave a comment

Umbraco Excel Macro that injects the Excell content into the RTE so it can be edited


Some code to to create an umbraco macro that takes an id of an excell sheet stored in the media lib

and shows it in the RTE, but normally you can edit the content of an excel sheet in an macro like dragging the borders to make the table bigger or to add custom styles.

&nbsp;

first create an umbraco macro, and open the view file in visual studio and add the following code

this code also uses ASPOSE to read in the excel file

<code>
<code>
@using System.Diagnostics
@using System.Web.Hosting
@using Aspose.Cells
@using Aspose.Cells.Tables;
@using System.Text;
@using ClientDependency.Core.Mvc
@using Newtonsoft.Json.Linq
@inherits Umbraco.Web.Macros.PartialViewMacroPage

@{
string datasource = Model.MacroParameters[“dataSource”].ToString();
string titel = Model.MacroParameters[“titel”].ToString();
var media = ApplicationContext.Current.Services.MediaService.GetById(Convert.ToInt32(datasource));
string path = HostingEnvironment.MapPath(media.Properties[“umbracoFile”].Value.ToString());
string tableId = string.Format(“media{0}”, datasource);
}
<div id=”exellDiv”>
@if (media != null)
{
using (FileStream stream = new FileStream(path, FileMode.Open))
{
Workbook book = new Workbook(stream);
if (book != null)
{
Worksheet sheet = book.Worksheets[0];
int rowCount = sheet.Cells.MaxDisplayRange.RowCount;
int columnCount = sheet.Cells.MaxDisplayRange.ColumnCount;

StringBuilder sb = new StringBuilder();

sb.AppendFormat(“<table id=\”{0}\” border=\”1\”>”, tableId);
for (int r = 0; r <= rowCount; r++)
{
sb.Append(“<tr>”);
for (int c = 0; c <= columnCount; c++)
{
Cell cell = sheet.Cells.GetCell(r, c);
if (cell == null)
{
continue;
}

sb.AppendFormat(“<td>{0}</td>”, Html.Raw(cell.HtmlString));

}
sb.Append(“</tr>”);
}
sb.Append(“</table>”);

<script>
tinymce.activeEditor.execCommand(‘insertHTML’, false, ‘@Html.Raw(sb.ToString())’);
tinymce.activeEditor.execCommand(‘mceRemoveControl’, false, ‘exellDiv’);
</script>
}
book.DisposeIfDisposable();
}
}
</div>

</code>

then in yr class that inherits from the  IApplicationEventHandler

add the following lines of code in the event

<code>
void PublishingStrategy_Publishing(IPublishingStrategy sender, PublishEventArgs<IContent> e)
{
foreach (var item in e.PublishedEntities)
{
// its a hackarround to remove the injector macro
// the macro reads an exell file, then injects it into the RTE, and removes the macro tag so it doesnt reload
if (item.ContentType.Alias.ToLower() == “***yourContentType***”)
{
if (item.Properties[“bodyText”].Value != null)
{
string bodyText = item.Properties[“bodyText”].Value.ToString();
bodyText = System.Text.RegularExpressions.Regex.Replace(bodyText, “<\\?UMBRACO_MACRO macroAlias=\”***aliasOfYourMacro***\” [^>]+>”, “”);
item.Properties[“bodyText”].Value = bodyText;
}
}

}
}
</code>

Posted in Umbraco | Leave a comment

Display image from umbraco 7 media picker in web page


Here is how to show an image from an umbraco 7 media picker, and show it on the web page

<img src=”@Umbraco.Media(CurrentPage.myImage).Url” alt=”@CurrentPage.title” />

Posted in Umbraco | Tagged , , , , | 3 Comments