Below you will find pages that utilize the taxonomy term “C-Sharp”
Trying out Visual Studio Code on Ubuntu
I am very curious about the new .NET Core, ASP.NET 5, EF 7 and Visual Studio Code for Linux, Mac and Windows. I have tried it out on an Ubuntu 15.04 machine. The installation and configuration required a few steps, so it is not an usual “Next-next-next”-installation. But, hey, it is just a beta, a preview so far, and first of all: It worked. I am sharing a couple of screenshots and the commands I ran in the terminal, mixed with comments and links: [source language=“bash”] #install latest node and npm #https://www.digitalocean.com/community/tutorials/how-to-install-node-js-on-an-ubuntu-14-04-server curl -sL https://deb.nodesource.com/setup | sudo bash - sudo apt-get install -y nodejs sudo npm install -g yo sudo npm install -g generator-aspnet # download VS Code and make a link # make a folder mkdir workspace/tryvs cd workspace/tryvs # create “src/global.json” file: # http://docs.asp.net/en/latest/tutorials/your-first-mac-aspnet.html { “sdk”: { “version”: “1.0.0-beta7” } } nano src/global.json # start VS Code # create # install omnisharp: # http://docs.asp.net/en/latest/getting-started/installing-on-linux.html#installing-on-debian-ubuntu-and-derivatives curl -sSL https://raw.githubusercontent.com/aspnet/Home/dev/dnvminstall.sh | DNX_BRANCH=dev sh && source ~/.dnx/dnvm/dnvm.sh dnvm #install dnx sudo apt-get install -y libunwind8 gettext libssl-dev libcurl3-dev zlib1g libicu-dev dnvm upgrade -r coreclr cd EmptyApplication dnu restore #install libuv #http://docs.asp.net/en/latest/getting-started/installing-on-linux.html#using-docker sudo apt-get install make automake libtool curl curl -sSL https://github.com/libuv/libuv/archive/v1.4.2.tar.gz | sudo tar zxfv - -C /usr/local/src cd /usr/local/src/libuv-1.4.2 sudo sh autogen.sh sudo ./configure sudo make sudo make install sudo rm -rf /usr/local/src/libuv-1.4.2 && cd ~/ sudo ldconfig #build, I got an error here dnu build #start the web server dnx web [/source]
Debugging "What's happening" in Communities
Recently an issue was reported about count mismatches in SharePoint 2013 Communities. The number of replies in category tiles sometimes is different compared to the community stats in the web part called “What’s happening”. The actual number of replies is 1 in the figure below. The user who has reported has tried to add, update and delete discussions and replies. I have invested some time debugging this issue. It would be pity to not share my findings. Well the first thing to do was to determine the type name for the “What’s happening” web part. To do so just edit the page and export the web part. In the exported .webpart file I saw that the type was Microsoft.SharePoint.Portal.WebControls.DashboardWebPart. With that knowledge it is time to open ILSpy, an awesome and free(!) assembly browser and decompiler. Load the “Microsoft.SharePoint.Portal” assembly from GAC into ILSpy. Then use F3 to search for DashboardWebPart: The number of replies is retrieved from SPWeb.AllProperties: If the Property Bag does not contain it, it gets the number of replies from the list. The formula is as follows: [code language=“csharp”] list.ItemCount - list.RootFolder.ItemCount [/code] It means that it gets the number of both discussions and replies: ItemCount of Discusssions List. The number of Discussions is determined by the ItemCount in the RootFolder of the Discussions List. Discussions are List Items in the RootFolder (num2 in the figure below). Replies are saved in the subfolders, every discussion gets an own folder. The number of all replies are num3 in the figure below. After checking the web properties I could see that the number of replies there were wrong: 2. The next step was to determine where and when the Web Properties are updated. The first guess every SharePoint Developer has in such cases is an EventReceiver. Here are all EventReceivers connected to the Discussions List: [code language=“powershell”] $list.EventReceivers | select class, Type, Synchronization | Out-GridView [/code] Allright, CommunityEventReceiver then: Found where the actual update happens: CommunityUtils.UpdateWebIndexedPropertyBag The method is used in DiscussionListCommunityEventHandler.HandleEvent There is a flag, flag5 that is used to determine if the Web Properties should be updated: But the flag5 is not true on Delete operations in some code flows: That’s it. So deleting a reply will not have any effect on “What’s happening”. But adding a new discussion will also update the stats: To summarize the debug session, there is an issue in the OOB code that misses to update community stats when deleting a discussion or a reply. Adding a new discussion, or a reply will synchronize the stats.
qoutes in @ strings
I use @-prefixed strings very often. You can use line breaks as much as you want. Very useful e.g. when I must create an xml in code. One thing I didn’t know was that you CAN use quotation marks inside @-strings. But you must write double quoutes like:
var t = @"säg ""hej""
och ""hå""";
Singleton vs static
Have you wondered what to use a singleton object or a class with static methods. Well, here is an awesome comparision of these techniques. Static methods and classes are easy to use, but you can’t them as objects, implement interfaces and have constructors with parameters.
A simple Log for ULS
Do an unsafe update in a unified manner « Sharepoint. Kunskap. Upptäckter på resan. - Sep 3, 2011
[…] Log class is my own class which I presented in my previous post. Like this:GillaBli först att gilla denna […]
A simple Log for ULS
Here is a simple log which has been inspired of Android Log. It logs to ULS which you can open with ULSViewer, SharePoint Log Viewer.
using System;
using Microsoft.SharePoint.Administration;
namespace Contoso.Intranet.Portal.Utilities
{
public class Log
{
private static readonly string \_CATEGORYNAME = "CONTOSO";
private static readonly SPDiagnosticsCategory \_ERROR\_CATEGORY =
new SPDiagnosticsCategory(\_CATEGORYNAME, TraceSeverity.Unexpected, EventSeverity.Error);
private static readonly SPDiagnosticsCategory \_WARNING\_CATEGORY =
new SPDiagnosticsCategory(\_CATEGORYNAME, TraceSeverity.High, EventSeverity.Warning);
private static readonly SPDiagnosticsCategory \_VERBOSE\_CATEGORY =
new SPDiagnosticsCategory(\_CATEGORYNAME, TraceSeverity.Verbose, EventSeverity.Verbose);
private static readonly SPDiagnosticsCategory \_INFO\_CATEGORY =
new SPDiagnosticsCategory(\_CATEGORYNAME, TraceSeverity.Medium, EventSeverity.Information);
private static void WriteTrace(SPDiagnosticsCategory category, string message, string trace)
{
SPDiagnosticsService.Local.WriteTrace(0, category, category.DefaultTraceSeverity, message, trace);
}
public static void Error(Exception ex)
{
WriteTrace(\_ERROR\_CATEGORY, ex.Message, ex.StackTrace);
}
public static void Warning(string message)
{
WriteTrace(\_WARNING\_CATEGORY, message, "");
}
public static void Verbose(string message)
{
WriteTrace(\_VERBOSE\_CATEGORY, message, "");
}
public static void Info(string message)
{
WriteTrace(\_INFO\_CATEGORY, message, "");
}
}
}
A possible improvement can be a custom Area. See an example of ThorstenHans on Github: CustomLogger.cs EDIT: I found an interesting article: How to log to the SharePoint ULS Logs: Clean Debugging and Error Logging broken down into steps written by Philip Stathis.
formatera int
Här finns en lista över formateringsmöjligheter med C# string.Format
String.Format("{0:00000}", 15); // "00015"
ForEach-metod i List
En intressant variant av foreach är ForEach-metoden i List. Titta på det lilla exemplet:
private static void SavePlacesToDB(SQLiteConnection cnn,
List<dynamic> places)
{
places.ForEach(obj => SavePlaceToDB(obj, cnn));
}
```Här används även det nya objektet [dynamic](http://msdn.microsoft.com/en-us/library/dd264736.aspx) som har kommit i Visual Studio 2010, samt en [lambda expression (=>)](http://msdn.microsoft.com/en-us/library/bb397687.aspx).
Binda Data till ListView i WPF
Det är väldigt smidigt att koppla datakälla till en ListView i WPF. Man skriver kod i XAML. Och i koden bakom anger man: myListView.ItemsSource = myList;
out ref
Om en metod har en inparameter med out framför sig. så innebär det att man skickar en referens till ett objekt. Alltså om det är out string param, så kommer det inte funka att skicka “någonting” direkt. Utan man måste instansiera först. string hej = “någonting”; CallTheMethod(ref hej); http://msdn.microsoft.com/en-us/library/t3c3bfhx(VS.80).aspx
kort variant av if-else
Inget speciellt egentligen med detta men vill skriva upp det här för att jag brukar glömma det. Det är samma syntax som i många andra språk:
bool value = "dit" == "dat" ? true : false;
Motsvarar:
bool value;
if ("dit" == "dat")
{
value = true;
}
else
{
value = false;
}
join i LINQ
LINQ är ett kraftfullt verktyg. Det som kan vara lite krångligt är join. Men om man gör rätt blir det bra. Låt oss titta på det sql-exemplet:
SELECT s.adAccount
FROM Staff s join StaffOnCourseInstance si
ON s.uid = si.uid
WHERE si.CourseInstanceId = 1435
För att köra motsvarande LINQ måste vi vara väldigt noga med on:
var testQuery = (from s in ctx.Staffs
join si in ctx.StaffOnCourseInstances
on s.uid equals si.uid
where si.CourseInstanceId == 1435
select new { s.adAccount });
```Edit 20101031: Det finns ett smidigare sätt att komma åt information i relaterade tabeller. Se mitt inlägg från 20101031 om [LINQ och foreign keys](https://sharepointkunskap.wordpress.com/2010/10/31/komma-at-andra-tabeller-via-foreign-keys-i-linq/).
keyword using {}
Ibland när man vill att ett objekt som man jobbar med är tungt och man vill slänga den direkt när man är färdig, så kan man använda keyword using…
public void Test()
{
using (SPweb web = site.OpenWeb("blabla")
{
//gör något och släng SPWeb-objektet
}
//.... metoden fortsätter
}
Men de objekten man använder i using, måste implementera interface IDisposable. Försök med using. Visual Studio säger ifrån om objektet av den typen inte implementerar IDisposable.
String.IsNullOrEmpty
I C# kan man testa om en sträng är null eller tom på ett enkelt sätt. I stället för att köra så:
string test;...
if (**test !=null && test != ""**)
{
//gör något.
}
Använder man en statisk metod String.IsNullOrEmpty(string value):
string test;...
if(**!String.IsNullOrEmtpy(test)**)
{
//do something
}