Category Archives: C Sharp

Get Monitor Size programmatically

Hello everyone,

today I want to show you how you can use C# to get the physical size of a monitor in inches. This can be helpful if you need to know the physical size of a monitor and you do not know where it is located or if you want to get a list of average monitor sizes in your company.

All you need to do to make this work is the below code snippet:

using System;
using System.Management;

namespace GetScreenSize
{
    class Program
    {
        static void Main(string[] args)
        {
            //Get monitor data
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(@"\root\wmi", @"SELECT * FROM WmiMonitorBasicDisplayParams");

            //Calculate and output size for each monitor
            foreach (ManagementObject managementObject in searcher.Get())
            {
                //Calculate monitor size
                double width = (byte)managementObject["MaxHorizontalImageSize"] / 2.54;
                double height = (byte)managementObject["MaxVerticalImageSize"] / 2.54;
                double diagonal = Math.Sqrt(width * width + height * height);

                //Output monitor size
                Console.WriteLine("Monitor Size: {0:F1}\"", diagonal);
            }

            Console.ReadLine();
        }
    }
}

If you have multiple monitors connected to your computer the above code will output the size of each monitor.

Important: You need to add a reference to System.Management to make the above code work.

Well, thatĀ“s it. Now you are able to get the physical size of your monitor without having to measure it.
I hope you liked my post and I hope to see you again next time šŸ™‚

As always you can download my code from here.

Sources:

http://www.c-sharpcorner.com/forums/get-the-monitor-size

https://richardspowershellblog.wordpress.com/2011/06/15/rootwmimonitor-information/

http://stackoverflow.com/questions/4314630/managementobject-class-not-showing-up-in-system-management-namespace

Advertisements
Tagged ,

SharePoint – Use Event Receiver to Auto-Increment columns

Hello everyone. Today a customer wanted a solution to automatically increment column values. Since he wanted to be able to configure the solution in a simple manner I decided to create an Event Receiver solution.

To create the solution log into your development machine and open Visual Studio. Choose Event Receiver as Project Template and deploy it as a Sandboxed solution.

Here is the code:

using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;

namespace AutoIncrement.EventReceiver1
{
/// <summary>
/// List Item Events
/// </summary>
public class EventReceiver1 : SPItemEventReceiver
{
/// <summary>
/// An item was added.
/// </summary>
public override void ItemAdded(SPItemEventProperties properties)
{
base.ItemAdded(properties);

using(SPWeb web = properties.Web)
{
int startValue = 0;
int incrementValue = 1;
String columnName = "";
int highestValue = 0;

//Query "AutoIncrementLists" for information
SPList list = web.Lists["AutoIncrementLists"];
SPQuery query = new SPQuery();
query.Query = String.Format("<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>" + properties.ListTitle + "</Value></Eq></Where>");
SPListItemCollection items = list.GetItems(query);

if (items.Count > 0)
{
//iterate through each Query Result
foreach (SPListItem item in items)
{
startValue = int.Parse(item["StartValue"].ToString());
incrementValue = int.Parse(item["IncrementValue"].ToString());
columnName = item["ColumnName"].ToString();

//Query current List for highest value
SPList incrementList = web.Lists[properties.ListTitle];
SPQuery incrementQuery = new SPQuery();
incrementQuery.Query = String.Format("<OrderBy><FieldRef Name='" + columnName + "' Ascending='False' /></OrderBy><RowLimit>1</RowLimit>");
SPListItemCollection incrementItems = incrementList.GetItems(incrementQuery);

//Check if query return items
if (incrementItems.Count > 0)
{
//Check if there are items with a value for the column columnName
if (incrementItems[0][columnName] != null)
{
highestValue = int.Parse(incrementItems[0][columnName].ToString());
}
}

SPListItem currentItem = properties.ListItem;

//Increment column
if (highestValue >= startValue)
{
currentItem[columnName] = highestValue + incrementValue;
currentItem.Update();
}
else
{
currentItem[columnName] = startValue + incrementValue;
currentItem.Update();
}
}
}
}
}
}
}

The code does the following:

It iterates through a Custom List called “AutoIncrementLists” and gets information from the columns Title, ColumnName, StartValue and IncrementValue. This information is used to update the current List Item which was added recently. (The solution I created only applies to Custom Lists.)

After you have created the solution you need to upload the solution to your Test site and activate it.

sharepoint_autoincrement_solutions

Now activate your Site feature. Mine is called “AutoIncrement for Custom Lists”.

sharepoint_autoincrement_site_feature

Next you need to create a Custom List called AutoIncrementLists and add the following columns:

  • Title (Single line of text): The Custom Lists Title
  • ColumnName (Single line of text): The Column Name
  • StartValue (Single line of text): The “Begin” of your Counter
  • IncrementValue (Single line of text): The value added to your Counter for each new item

You need this list on every site you want to use this feature.

sharepoint_autoincrement_settings_list

Here is an example of my “AutoIncrementLists” list:

sharepoint_autoincrement_settings_list_example

Here is the example of the “AutoInc1” list:

sharepoint_autoincrement_example1

And here is the example of the “AutoInc2” list:

sharepoint_autoincrement_example2

ThatĀ“s it. Now you have a solution which allows you to automatically increment your columns every time an item is added. I hope you liked my post. See you next time.

As always you can download my code from here.

Sources:

http://social.technet.microsoft.com/forums/sharepoint/en-US/39743bb3-872d-4788-96a8-2b9fb8813011/create-auto-increment-value-in-sharepoint-column

http://faisalrafique.wordpress.com/2011/03/19/creating-auto-increment-field-in-sharepoint-list/

http://stackoverflow.com/questions/15929903/sharepoint-list-item-throws-null-error

http://stackoverflow.com/questions/3903986/programmatically-setting-field-value-for-sharepoint-listitem

https://theezitguy.wordpress.com/2014/08/22/sharepoint-event-receiver-to-prevent-documents-from-being-deleted/

Tagged ,

SharePoint – Event Receiver to prevent documents from being deleted

Hello everyone. A few days ago I got a request to find a solution for the following problem: My customer has some Document Libraries where he stores important documents. These documents mustnĀ“t be deleted since those documents are important contracts. So what can you do to prevent this?

Well there are some ways to achieve this: You can create a new Permission Level which does not allow the Delete action or you can create an Event Receiver which cancels the Delete action and throws an error message. I chose the second option since my customer and I both wanted to provide the user some information why his Delete action was canceled. (The first option would simply grey out the Delete action possibly resulting in users thinking there is something wrong with the software system.)

To create the Event Receiver do the following:

First open up Visual Studio on your Development machine and choose New Project. Select Event Receiver as your project template.

sharepoint_deleting_event_receiver

Next I chose Deploy as a sandboxed solution. (A sandboxed solution is enough for our planned actions.)

sharepoint_deleting_event_receiver_sandbox

Next select Document Library from the Dropdown and check An item is being deleted as event.

sharepoint_deleting_event_receiver_settings

And here is the code:

using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;

namespace SPDeletedReceiver.EventReceiver1
{
/// <summary>
/// List Item Events
/// </summary>
public class EventReceiver1 : SPItemEventReceiver
{
/// <summary>
/// An item is being deleted.
/// </summary>
public override void ItemDeleting(SPItemEventProperties properties)
{
base.ItemDeleting(properties);

using(SPWeb web = properties.Web)
{
SPList list = web.Lists["DoNotAllowDelete"];
SPQuery query = new SPQuery();
query.Query = string.Format("<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>" + properties.ListTitle + "</Value></Eq></Where>");
SPListItemCollection items = list.GetItems(query);

if(items.Count > 0)
{
properties.ErrorMessage = "You are not allowed to delete items.";
properties.Status = SPEventReceiverStatus.CancelWithError;
properties.Cancel = true;
}
}
}
}
}

Code Explanation: The actions of the code are not very complex. What it simply does is check if the List Title of the List where the Delete action was triggered is listed in a Custom List called “DoNotAllowDelete”. If the List Title is listed the Delete action will be canceled. If not the Delete action will be executed.

So you are basically black listing some Document Libraries where the Delete action is forbidden for everyone.

To use the Event Receiver you need to upload the solution wsp file to your Solutions in your Site Collection and activate it. And you must activate the Event Receivers feature on the sites (Site features) where you want to use the solution.

Important: You also need to create a Custom ListĀ called “DoNotAllowDelete” on each Site you want to use the solution. And you need to enter the Library Titles of your black listed Document Libraries into the Title column of this list.

Here is an example picture of my “DoNotAllowDelete” list:

sharepoint_event_receiver_donotallowdelete

As you can see I black listed the Document Library “Documents”. If I now try to delete a document is the “Documents” library I will receive an error message like you can see below and the the document will not be deleted.

sharepoint_deleting_event_receiver_error_message

Well thatĀ“s it. I hope my post was interesting for you. See you next time.

As always you can download my code from here.

Sources:

http://planetlotus.org/profiles/bram-nuyts_116783_prevent-items-from-being-deleted-using-an-event-receiver

Tagged ,

SharePoint – Change Date Format

Hello everyone. A while ago I got the request to change the date format of SharePoint. The company IĀ“m working for has all SharePoint Site Collections setup using the Culture en-US and therefore the date format looks like this: MM/dd/yyyy. Since this date format can be quite confusing for our international employees we decided to replace it with the ISO8601 date format. The solution was quite simple:

Prerequisites:

  • Microsoft Visual Studio

The first thing you need to do is to create a new Console Application.

The next thing you need to to is to add a reference to sysglobl.dll.

And here is the code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;

namespace DateTimeFormat
{
class Function
{
public void SetDateFormatISO8601()
{
try
{
CultureAndRegionInfoBuilder.Unregister("en-US");
}
catch
{
}

CultureAndRegionInfoBuilder builder = new CultureAndRegionInfoBuilder("en-US", CultureAndRegionModifiers.Replacement);
builder.LoadDataFromCultureInfo(new CultureInfo("en-US"));
builder.LoadDataFromRegionInfo(new RegionInfo("en-US"));
builder.GregorianDateTimeFormat.ShortDatePattern = "yyyy-MM-dd";
builder.Register();
}

public void SetDateFormatAmerican()
{
try
{
CultureAndRegionInfoBuilder.Unregister("en-US");
}
catch
{
}

CultureAndRegionInfoBuilder builder = new CultureAndRegionInfoBuilder("en-US", CultureAndRegionModifiers.Replacement);
builder.LoadDataFromCultureInfo(new CultureInfo("en-US"));
builder.LoadDataFromRegionInfo(new RegionInfo("en-US"));
builder.GregorianDateTimeFormat.ShortDatePattern = "MM/dd/yyyy";
builder.Register();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DateTimeFormat
{
 class Program
 {
 static void Main(string[] args)
 {
 Function function = new Function();

 string Choice = string.Empty;
 Console.WriteLine("Set Date format of Site Collection:");
 Console.WriteLine("-----------------------------------");
 Console.WriteLine("1) Set Date format to ISO8601 standard format (yyyy-MM-dd)");
 Console.WriteLine("2) Set Date format to default american format (MM/dd/yyyy)");
 Console.WriteLine();
 Console.WriteLine("Choose a number:");
 Choice = Console.ReadLine();
 Console.WriteLine();

 if(Choice == "1")
 {
 function.SetDateFormatISO8601();

 Console.WriteLine("Done");
 Console.ReadLine();
 Console.WriteLine();
 }
 else if (Choice == "2")
 {
 function.SetDateFormatAmerican();

 Console.WriteLine("Done");
 Console.ReadLine();
 Console.WriteLine();
 }
 else
 {
 Console.WriteLine("Invalid input");
 Console.ReadLine();
 Console.WriteLine();
 }
 }
 }
}

ThatĀ“s it. Your code is ready to use.

Please remember to run the code as Administrator. Otherwise the User Account Control will stop your program.

After you have successfully run the code you need to run cmd as Administrator and run the following command:

iisreset

ThatĀ“s it. Now all Site Collections configured to use the Culture en-US will display their date format like this: yyyy-MM-dd.

Important: I did not come up with the code above. I just used the code I found here. The post was pretty useful for me so I thought I should share it.

I hope my post was useful for you and as always you can download my code from here.

Sources:

http://www.matdesmarais.com/2011/12/changing-the-date-display-format-in-sharepoint-2010/

Tagged ,

C# – Convert DOC to DOCX

Hello everyone. Today I tried to figure out how I can convert doc files to docx files by using C#. Well, and I came up with the below example.

The prerequisites for this solution are:

  • Visual Studio
  • Microsoft Office installed on the machine where you want to run this application

Now I will explain the necessary steps.

The first thing you need to do is to add a reference by clicking on Add Reference…

visual_studio_doc_to_docx_add_reference

Now search for Microsoft Word 14.0 Object Library (The version number 14 represents Microsoft Office 2010. Version number 15.0 represents Microsoft Office 2013) and click OK.

visual_studio_doc_to_docx_microsoft_word_object_library

Important: Make sure you have a version of Microsoft Office installed on your Development machine. Otherwise you will not find the reference you need.

Now for the code. Here you go:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace DOCToDOCX
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void browse_Click(object sender, EventArgs e)
{
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
pathTextBox.Text = openFileDialog1.FileName;
}
}

private void convert_Click(object sender, EventArgs e)
{
Function f = new Function();

f.ConvertDOCToDOCX(pathTextBox.Text);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Interop.Word;
using System.IO;

namespace DOCToDOCX
{
class Function
{
public void ConvertDOCToDOCX(string path)
{
Application word = new Application();

if(path.ToLower().EndsWith(".doc"))
{
var sourceFile = new FileInfo(path);
var doc = word.Documents.Open(sourceFile.FullName);

string newFileName = sourceFile.FullName.Replace(".doc", ".docx");
doc.SaveAs2(FileName: newFileName, FileFormat: WdSaveFormat.wdFormatXMLDocument, CompatibilityMode: Microsoft.Office.Interop.Word.WdCompatibilityMode.wdWord2010);

word.ActiveDocument.Close();
word.Quit();
}
}
}
}

Important: If you remove the following line of code from the above code your documents will stay in Compatibility Mode after they were converted to docx files.

CompatibilityMode: Microsoft.Office.Interop.Word.WdCompatibilityMode.wdWord2010

ThatĀ“s it. Pretty simple, right? Hopefully my post was interesting for you. And as always you can download my code from here.

Sources:

http://justgeeks.blogspot.co.at/2011/09/convert-batch-of-doc-files-to-docx.html

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

http://row5is.wordpress.com/2012/07/06/convert-doc-to-docx-using-powershell/

http://msdn.microsoft.com/en-us/library/microsoft.office.tools.word.document.saveas2.aspx

Tagged

C# – Create DOCX from HTML code

Hello everyone. Today I was playing around to find out how to convert HTML code to Word documents (.docx). I think I found a very simple solution to do this. All you need is Visual Studio and a dll you can download from here.

For my example I created a new Windows Forms Application.

DOCXToHTML_project

The next step is to add a reference to the dll “HTMLtoDOCX.dll”.

DOCXToHTML_reference_dll

Now here is the code I used for my example application:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace CreateDOCXFromHTML
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void browse_Click(object sender, EventArgs e)
{
saveFileDialog1.Title = "Save file as...";
saveFileDialog1.Filter = "Word Document (*.docx)|*.docx|All files (*.*)|*.*";
saveFileDialog1.RestoreDirectory = true;

if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
path.Text = saveFileDialog1.FileName;
}
}

private void save_Click(object sender, EventArgs e)
{
Function f = new Function();
string data = f.GetHTMLfromUrl(url.Text);

NoInkSoftware.HTMLtoDOCX NewFile = new NoInkSoftware.HTMLtoDOCX();
NewFile.CreateFileFromHTML(data, path.Text);

MessageBox.Show("Save to DOCX finished.");
url.Text = "";
path.Text = "";
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace CreateDOCXFromHTML
{
class Function
{
public string GetHTMLfromUrl(string Url)
{
string data = string.Empty;

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream receiveStream = response.GetResponseStream();
StreamReader readStream = null;
if (response.CharacterSet == null)
readStream = new StreamReader(receiveStream);
else
readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
data = readStream.ReadToEnd();
response.Close();
readStream.Close();
}

return data;
}
}
}

My example application needs the following input to work:

Here is an example document I created from my previous post:

DOCXToHTML_finished_docx

As you can see the result is not perfect but still very good. I hope my post was useful and interesting for you šŸ™‚

And as always you can download my example from here.

Important: I did not create this solution on my own. I got the code from here. Please give this guy some credit for his great work.

Sources:

http://www.codeproject.com/Articles/91894/HTML-as-a-Source-for-a-DOCX-File

http://stackoverflow.com/questions/16642196/get-html-code-from-a-website-c-sharp

http://www.csharpdeveloping.net/Snippet/How_to_create_file_save_dialog

Tagged