Hiding and showing HTML elements with ASP .NET

Hi,

Ok, this is probably a quite simple thing to do and maybe everyone knows it BUT just in case… :).

Well, you need two things a C# code(or some other way to ouput HTML) to generate and anchor link by which to display or hide a given HTML element.

In this case, let’s say that you have a DIV element. You assign as the ID value the client ID which your control receives from ASP .NET(notice that the unique ID or the ID but the ClientID, it is HTML friendly).

Then you would do something like the code below. You are calling a JavaScript function which receives as parameters the full ID for the DIV element and the start of the DIV full id.

The idea is to be able to identify all of the elements which are under this same hide and show logic while still being able to identify a single item.

Exmaple ID:
id =”cars_ASP.NETUserControlClientID_carnumber”

The bolded part would be used to identify ALL of the items which need be processed at the same time. While the non-bolded value(carnumber) is the identifier for a single item.

The C# code below creates an anchor calling the function below the C# code. Notice the href definition “javascript:void(0)“, this is to avoid page jump in certain browsers and their versions.

String.Format("<a href=\"javascript:void(0)\" onclick=\"showInfo('{0}','{2}')\">{1}</a>", "HTML Element ID to find unique counter or ID" + this.ClienID, "The link title/name", this.ClienID);

function showInfo(id, controlUniqueID) {
// Search for all items and hide them
 $('*[id*=' + controlUniqueID + ']').each(function () {
 $(this).hide();
 });

// Next open only the item which you want to see
 if ($('#' + id).css('display') == 'none') {
 $('#' + id).show();
 }
 else {
 $('#' + id).hide();
 }

 }

Mobile Device Testing and Debugging with VirtualBox, Android Studio, Visual Studio and IIS

This post is from the perspective of a person who has a Microsoft technologies based web solution that needs to connect with a mobile device. This might work for other types of technologies and virtual machines with some or alot of tuning. Basic principles should be more or less the same.

I will give firstly an introduction on the solution used in my scenario:

I have a Android mobile device with an app in it that needs to connect to a webapi service to retrieve data and post data to it. The thing which this post is concerned about, is debugging the app with Android studio using the app from the Android device against a webapi which is also under debug mode in Visual Studio. This way I can see what is happening both on the client and on the server side.

Basically how this works is that you will have to connect with your mobile device to a local network where your physical machine exists. Because you are using a mobile device the logical way is over WiFi and no having your device plugged in to your physical machine by USB does not work. You can not directly connect to a localhost that way. Well atleast I could not make it to work. Notice that you can connect to a localhost from Android Studio while debugging your Android app but this is only possible is your a emulating the app locally. Even then though you might have problems and have to configure your solution in such a way that your app will pick it up.

This post assumes that you have a ready build for your server side solution at a location in your development machine. Here are the steps:

1. Create IIS site

– Add a new application to IIS which points to your solution build location.
mobile1

mobile2

– Next make sure that the application pool account has enough privileges to the location. I do this by creating a new account to AD or I create a local machine account on my development machine.

This is to configure the Application Pool account:
mobile8

These steps are for the file system level:
mobile3

mobile4

– If you are using a database in your application make sure that the application pool account has the proper privileges. This depends of course on how you have built your solution.
– Assign a port to your web application

mobile6

mobile5

2. Config ports and firewall settings
– Next you need to allow inbound and outbound connections to you web application through the port which was earlier configured for the web application. This needs to be done for both the virtual machine and your actual physical machine.

For virtualBox:
mobile9

For WMWare:
mobile10
mobile11

3. Attach to process

The next steps is to attach your developer tools to your server solution and your mobile application to whatever developer tools your are using, something like Android Studio or XCode.

Config VirtualBox

How to Forward Ports to a Virtual Machine and Use It as a Server

 

SharePoint Tip – Fixing unresponsive Edit mode when trying to add content

This is a tip on how to solve the issue in the title. This can occur to you when you open a page for editing and focus your mouse on the main content area. Normally the content editor should become active in the ribbon but this may not happen or you just can not add content.

This can be due to a possible JavaScript library performing some action on the page or worse a webpart which is inserted within the content area. This webpart uses a JS library and functionalities which interfere with the SharePoint out of the box content editor. This happened to me with HighCharts.

The solution for this is to add the following URL postfix after you aspx page ?contents=1.

Next you should be able to select the webparts which you know are in your content area. Close those selected webparts (you may need  to check out the page). After this go back to your page and add new content. When you are ready then focus your mouse in the content area to add a new webpart. Your webpart should be under a category named something like “Closed webparts”. Add the webpart and everything should be OK. The webpart properties and state should have stayed as it where before it was closed.

 

VirtualBox, Android Devices and error “This device cannot start. (Code 10)”

Ok, if you get this error you are probably trying to install your Android device to windows and it fails. When checking the device manager you might see the following error code. There are numerous posts and instructions which might help you but none did to my LG G3. What eventually helped was an insight based on several different posts.

On my virtual machine the problem was related to the USB port type used in relation to the USB port actually used in your real world machine and USB cable used.

Basically as default the VirtualBox used USB 1.1 which for some reason does not work, probably something to do with my cable being USB 2.0. To fix my problem I installed the VirtualBox extension for USB: VM VirtualBox Extension Pack.

Then I changed the USB type to be used for the Virtual Machine to 2.0, booted my windows and it worked. So if you are getting the error above no matter where you are check that you have the proper USB cable which is compatible with your Android device and the port on your machine. For a virtual machine image check that you have the right USB configuration in relation to your real world devices.

If the case above does not work, then try this KB article from Microsoft:

https://support.microsoft.com/en-us/kb/943104

SharePoint Excel Services Loading Excel files from code

If you ever wondered how you might load an Excel Sheet from an Excel file dynamically from a webpart then this is your lucky day :). Well below is the code how to do it.

The code below is rather simple. You have an excel file URL within SharePoint which is used to retrieve data to build a excel web services URL from where the actualy HTML based excel data is retrieved.

There are two points to be made:
1. During the development of this functionality I noticed that without the definition for the headers excel services would not always operate as expected. This was especially true when in anonymous mode, in other words a public site.
2. If you are going to ry to use excel services through code like in this example you also need to take into consideration access. Under a Windows Authentication model you have no problems but if you use anonymous access you are going to have problems. so if you encounter problem with public sites consider creating an AD account which is going to be used as the anonymous user in IIS for your SharePoint application. Then to allow access to the target excel file location simply add the minimum privileges of “Read” to the account. Add these rights either to the library where the file is located of the file itself.

private String excelWebServicesURL = "{0}/_vti_bin/ExcelRest.aspx/{1}/model/Ranges('''{2}''!{3}|{4}')?$format=html";

String composedExcelWebServicesURL = null;
            try
            {
                if (!String.IsNullOrEmpty(this.ExcelFileLocation) && !String.IsNullOrEmpty(this.ExcelSheetName) && !String.IsNullOrEmpty(this.ExcelSheetStartCell) && !String.IsNullOrEmpty(this.ExcelSheetEndCell))
                {
                    using (SPSite site = new SPSite(this.ExcelFileLocation))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            SPFile excelFile = web.GetFile(this.ExcelFileLocation);
                            if (excelFile != null)
                            {
                                String hostName = null;
                                if (!string.IsNullOrEmpty(Request.Url.Query))
                                {
                                    hostName = Request.Url.AbsoluteUri.Replace(Request.Url.Query, String.Empty);
                                    hostName = hostName.Replace(Request.Url.AbsolutePath, String.Empty);
                                }
                                else
                                {
                                    hostName = Request.Url.AbsoluteUri.Replace(Request.Url.AbsolutePath, String.Empty);
                                }
                                Uri webURI = new Uri(web.Url);
                                String presentWebReformedURL = hostName + webURI.AbsolutePath;
                                composedExcelWebServicesURL = String.Format(this.excelWebServicesURL, presentWebReformedURL, excelFile.Url, this.ExcelSheetName, this.ExcelSheetStartCell, this.ExcelSheetEndCell);

                                if (this.DebugMode == true)
                                {
                                    this.lDebugInfo.Text += composedExcelWebServicesURL != null ? composedExcelWebServicesURL : "URL data is empty";
                                }
                                using (var client = new WebClient())
                                {
                                    var newUri = new Uri(composedExcelWebServicesURL);
                                    var myProxy = new WebProxy();
                                    myProxy.Credentials = CredentialCache.DefaultCredentials;
                                    myProxy.Address = newUri;
                                    client.Proxy = myProxy;

                                    client.Encoding = System.Text.Encoding.UTF8;
                                    client.Headers.Add("User-Agent", @"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)");
                                    client.Headers.Add("Accept", @"text/html, application/xhtml+xml, */*");
                                    if (this.DebugMode == true)
                                    {
                                        this.lDebugInfo.Text += "</br> Before download string";
                                    }
                                    this.lExcelWebServiceHTML.Text = client.DownloadString(composedExcelWebServicesURL);
                                    if (this.DebugMode == true)
                                    {
                                        this.lDebugInfo.Text += "</br> After download string";
                                    }
                                }
                            }
                        }
                    }
                }
				}
            catch (Exception ex)
            {

            }

SharePoint – Setting users or groups for a membership webpart through code

This is a rather simple thing… well once you have cracked it :).

 

There are two properties which need to be set:

And that is it. To find the “main” associated groups to your site you could use these properties:

https://msdn.microsoft.com/EN-US/library/microsoft.sharepoint.spweb.associatedownergroup.aspx

https://msdn.microsoft.com/EN-US/library/microsoft.sharepoint.spweb.associatedmembergroup.aspx

https://msdn.microsoft.com/EN-US/library/microsoft.sharepoint.spweb.associatedvisitorgroup.aspx

https://msdn.microsoft.com/EN-US/library/microsoft.sharepoint.spweb.associatedgroups.aspx


using (SPSite site = new SPSite(wsSite.ID))
{
using (SPWeb web2 = site.OpenWeb(wsSite.RootWeb.ID))
{
var pubWeb = PublishingWeb.GetPublishingWeb(web2);

using (var wpm = pubWeb.DefaultPage.GetLimitedWebPartManager(PersonalizationScope.Shared))
{
// Search for the right webpart(you could use LINQ instead of a foreach)
int memberShipWebPartsCount = 0;
for (int x = wpm.WebParts.Count - 1; x >= 0; x--)
{
var membersWebPart = wpm.WebParts[x] as Microsoft.SharePoint.WebPartPages.MembersWebPart;
if (membersWebPart != null)
{

// There are only two members webparts which are needed to be processed, at the moment
if (memberShipWebPartsCount < 2)
{
if (memberShipWebPartsCount == 0)
membersWebPart.MembershipGroupId = wsSite.RootWeb.AssociatedOwnerGroup.ID;
else if (memberShipWebPartsCount == 1)
membersWebPart.MembershipGroupId = wsSite.RootWeb.AssociatedMemberGroup.ID;

membersWebPart.DisplayType = Microsoft.SharePoint.WebPartPages.MembersWebPartDisplayType.GroupMembership;
wpm.SaveChanges(membersWebPart);

pubWeb.DefaultPage.Update();
if (pubWeb.DefaultPage.CheckOutType != SPFile.SPCheckOutType.None)
pubWeb.DefaultPage.CheckIn("");

if (pubWeb.DefaultPage.ParentFolder.DocumentLibrary.EnableVersioning && pubWeb.DefaultPage.ParentFolder.DocumentLibrary.EnableMinorVersions)
pubWeb.DefaultPage.Publish("");
}
memberShipWebPartsCount++;
}
}

}
}
}