Monday, 30 January 2012

Automatic converting Word file to PDF with replace

Word Automation Services available in SharePoint 2010 supports converting Word documents to other formats. This includes PDF. 
Following MSDN article describes step-by-step how to create Event Receiver, add proper libraries and code. Unfortunately, this creates new copy of PDF file, while I wanted the file to be overwritten to the same item. 

Instead of starting a job, that creates new file, I start conversion job that overwrites the file: 
pdfConversionJob.AddFile(wordFileName, wordFileName);

This creates file in the same item, but now you won't be able to open it, since SharePoint still treats this file as Word document. It would be great, if i could just change file name in ItemUpdated receiver. Problem is, that this job does not trigger Event Receivers. 
I put a waiting loop, that waits until job is finished (or until timeout passes):
int finishedConversionCount = cjStatus.Succeeded + cjStatus.Failed;
while ((finishedConversionCount != 1) && ((DateTime.Now - conversionStarted) < timeSpan))
{
    // wait one minute
    System.Threading.Thread.Sleep(60000);

    cjStatus = new ConversionJobStatus(wordServiceApplicationProxy, pdfConversionJob.JobId, null);
    finishedConversionCount = cjStatus.Succeeded + cjStatus.Failed;
} 
Then I have to change the name of the file. To do this, I use MoveTo method:
SPFile wordFile = properties.ListItem.File;
wordFile.MoveTo(pdfFileName, true);

The full Event Receiver code can be found here.


Thursday, 26 January 2012

Using GUID instead of class name

I will demonstrate on example of adding Event Receiver.

Create Event Receiver, open class file.
First add this:
using System.Runtime.InteropServices;

Then add this above class (use GUID Generator):
[Guid("567de298-a813-42ad-a639-26af24ad77b0")]
public class GoleszympansyEventReceiver : SPItemEventReceiver

Now, let's imagine you want to change class name or namespace. You'll have to change it also in Elements.xml.
But not anymore. Just insert this into elements.xml:
<Class>$SharePoint.Type.567de298-a813-42ad-a639-26af24ad77b0.FullName$</Class>

Guid here MUST be lower case. Just paste Guid from GUID Generator and then select it and press Ctrl+U.

Now the compiler will take care of the rest.

Full list of replaceable parameters can be found here: http://msdn.microsoft.com/en-us/library/ee231545.aspx

Friday, 13 January 2012

Adding snippets in Visual Studio

In this example I will create a snippet, that surrounds code block and makes it run with elevated privileges.

1. Go to

2. Create new text file, rename with .snippet extension
3. Open for edit in Notepad
4. Insert this code:

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <Title>SPSecurity.RunWithElevatedPrivileges</Title>
      <SnippetTypes>
        <SnippetType>Expansion</SnippetType>
        <SnippetType>SurroundsWith</SnippetType>
      </SnippetTypes>
    <Shortcut>spsec</Shortcut>
    </Header>
    <Snippet>
      <Code Language="csharp">
        <![CDATA[SPSecurity.RunWithElevatedPrivileges(delegate
            {
                $selected$ $end$
            });]]>
      </Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>

5. What you need to customize:
  • Title
  • Shortcut - this is how you use snippet
  • Language (XML, csharp, VB)
  • Code - insert it always between <![CDATA[ and ]]>
  • Put $selected$ where your surrounded code block should be
6. Save file
7. Test it:






This snippet is available here. And here is another link with snippet that adds two using blocks for SPSite and SPWeb.

More documentation on snippets: http://msdn.microsoft.com/en-us/library/ms171418.aspx

Thursday, 12 January 2012

Austrian company registration number (Firmenbuchnummer) generator

I created a small web app, that generates a valid company number (in German: Firmenbuchnummer) of Austrian companies. It correctly computes control letter (how?). It is not real existing number, but at least it should pass most validations.
You can find the app here: http://bit.ly/firmenbuchnummergenerator.

By the way, here's what I think about the service that hosts the app.

Hosting ASP.NET project with aspspider.net

The only really free ASP.NET hosting provider that I could find is AspSpider.NET. You can register here.

Althougt site is infested with ads, and it's not easy to navigate, it offers real service without any hidden charges or popup ads on your site.

After you register, you have to wait 30 minutes before you can upload your files. I don't know why. You can upload your project and it's possible to use database by uploading MDF file.

Some time ago AspSpider used to delete projects if you didn't log into them for 3 months, so unfortunately you cannot just create your app and leave it there.

Good thing is, that after 3 months from your last login, AspSpider will send an e-mail that reminds of logging in. If you don't login within 7 days, they will delete your account. 

Wednesday, 11 January 2012

Working remotely on your computer

I think everyone knows Remote Desktop. In Windows it allows you to remotely access another Windows machine. All you need to connect is to know password of local user or have your domain user added to Remote Users Group. You connect by IP address or computer name, so your computers must "see" each other on the network.
But what if...
If the computer you want to connect to is behind firewall that cuts off RDP? Or it is inside of private network, and you're currently outside of it? Like when that time you wanted to connect to your work computer from home?

There are some tools, that let you connect to your PC from anywhere via web browser. This way you can connect inside private network and you bypass firewalls (connection is made via HTTP).

LogMeIn
This company provides free and universal tool to connect to computer with web browser. You need to register you account on their website, install client app on remote computer and then, when the app is running you can see it in your browser. You can connect to this PC by simply clicking it in the browser.

BTW, this company makes another product, Hamachi, which makes it really easy to create VPN between two computers. I think it's mostly used by gamers, who want to connect several computers anywhere on internet into private network and play, but can have also commercial applications.

Windows Live Mesh
This application is part of Windows Live essentials (or I'd say suite). You need your WindowsLiveID to login. One purpose of Mesh is to synchronize folders on different machines. It uses your SkyDrive space to store data in The Cloud.

But also, you can use Mesh to remotely control your PC. First add your machine by either clicking "Add this computer" in devices.live.com, or using the Mesh console. Then, in your Windows Live Mesh console go to "Remote" and click on "Allow remote connections to this computer".
Now when you go to devices.live.com, you'll see all your devices and some will have link "Connect to this computer". Click it and connect.

Comparing the two
With Mesh, you are allowed to only use The Chosen One, i.e. you need to use Internet Explorer 6 or later (32-bit version only). LogMeIn will let you use any browser, so you can connect even from iPad or different OS.
LogMeIn lets you choose resolution and color scheme for your connection, so in case of slow connection you can work comfortably. In Mesh you will be working with native resolution of your host. It has however a panel, where you can zoom in and out an pan your screen.
LogMeIn will let you connect even to the computer, where you currently work, and so you may see your remote screen within your screen within your screen etc. (looks funny, but not useful). Mesh will give you a warning.
Both programs can be used for free. LogMeIn has several plans, both free and pro. Mesh is included in Windows Live Essential, so chances are that you already have it in your computer.



Tuesday, 10 January 2012

Interesting links on Twitter

If you use twitter, the blog now has its own account, that you can follow. This way you will never miss another blog post. Follow: @GoleSzympansy
Additionally, I have account, where I share links I find interesting. Some are about SharePoint and programming, and some aren't. Follow: @links_from_olo

This task requires the application to have elevated permissions.

Problem:
I start my Visual Studio 2010, create new SharePoint project and after giving project name and clicking OK I get this error:
This task requires the application to have elevated permissions.

I already started VS2010 as administrator, but that's not the solution yet.

Solution:
I log to the server via Remote Desktop with my domain account. To be able to connect VS to SharePoint, my account needs to be added to local administrators group (get your admin/domain admin to do that).
Afterwards, I need to log out from Windows (thus ending my session) and log in again. Now, when I run Visual Studio as administrator, I can create new SharePoint project. 

Tuesday, 6 December 2011

Jak zainstalować Windows 7 bez użycia DVD

Jeśli ściągniesz sobie obraz płyty ISO z wersją instalacyjną Windows (np. z MSDN) i chcesz go zainstalować, najłatwiej jest wypalić go na DVD i zainstalować z płyty. Ale co, jeśli nie masz w swoim laptopie lub netbooku stacji DVD? Lub nie chcesz wypalać płyt?

Windows 7 można bez problemu zainstalować z USB. Potrzebujesz do tego wolnego pendrive o odpowiedniej pojemności, co najmniej 4 GB. Pobierz sobie najpierw Windows 7 USB/DVD download tool. Zainstaluj go na swoim komputerze. Uruchom. Włóż pendrive do USB. W prostym kreatorze, w czterech krokach zostanie przygotowany instalacyjny USB. Podajesz lokalizację pobranego pliku .iso z instalką Windows, wybierasz urządzenie USB a potem czekasz. Gdy proces przygotowania się skończy, nie wyciągając pendrive'a zresetuj komputer. Upewnij się, że w BIOS-ie masz ustawioną możliwość startowania systemu z dysku USB i wybierz ją.

Komputer uruchomi się z klucza USB i pojawi się instalator systemu. Teraz już wykonujesz tylko kolejne polecenia na ekranie.
Jeśli uaktualniasz system, twoje stare pliki i dokumenty znajdą się w katalogu C:\Windows.old. Więcej o tym katalogu pisałem tutaj.

Sztuczki z adresami bloga

Ostatnio zarejestrowałem nowy adres dla bloga. Było za darmo, więc co mi tam. Nowy adres to www.goleszympansy.pl.
Jaki z tego wynika problem? Otóż chcę, by blog byl dostępny pod wszystkimi adresami - a przynajmniej żeby wszystkie przekierowywały w jedno miejsce.

Rozwiązanie znalazłem nie całkiem łatwo na forum i tym blogu oraz za pomocą kilku prób i błędów.

Na początek: jak Google (i Windows Live) obsługuje custom domains
W ustawieniach swojej domeny należy nadać rekord CNAME do ghs.google.com (a w przypadku firmy konkurencyjnej jest to go.domains.live.com). Serwer docelowy na podstawie nagłówka HOST z żądania HTTP  (czyli tego, co zostanie wpisane w przeglądarkę) "wie", co wyświetlić.

Problem główny:
W tej chwili podstawowym adresem jest i ma być www.goleszympansy.pl (tak, przeniosłem z .eu na .pl). Wpisanie goleszympansy.blogspot.com przenosi na powyższy i wyświetla blog. Na starym goleszympansy.eu ustawiłem przekierowanie na podkatalog. W efekcie wpisanie tego adresu lub kliknięcie na dowolny permalink poniżej tego adresu, który mógłby być zindeksowany przez wyszukiwarkę będzie wprawdzie wyświetlał właściwą podstronę, ale w ramce. Natomiast www.goleszympansy.eu, o dziwo, przenosi na stronę www.google.pl. Z kolei goleszympansy.pl (czyli bez www) pokazuje zaślepkę home.pl.

Rozwiązanie: problem najłatwiejszy, czyli zaślepka home rozwiązałem w banalny sposób - w przekierowaniu WWW trzeba było również wpisać ghs.google.com. A w ustawieniach Bloggera koniecznie zaznaczyć "Przekierowanie z domeny goleszympansy.pl do domeny www.goleszympansy.pl.". Również jeśli wchodząc na swój adres bez www zobaczysz popsutego robocika (błąd 404), musisz wykona powyższe kroki.

Problem z www.goleszympansy.eu rozwiązał się sam, jak tylko rozpropagowały się wpisy DNS. Wcześniej dla testów skierowałem rekord www na goleszympansy.blogspot.com. W rzeczywistości ten drugi adres też kieruje dalej, na blogspot.l.google.com. A ponieważ nigdzie nie poinformowałem, do czego mój host ma kierować, wyświetliła się strona google.com

Ostatni problem, czyli ramka dla adresu goleszympansy.eu, to niestety tylko obejście. Wprawdzie blog nadal jest dostępny, ale kliknięcie dowolnego linku wewnątrz nadal pozostawia w przeglądarce wcześniejszy adres. Może to wpłynąć niekorzystnie np. na indeksowanie w wyszukiwarkach oraz mylić użytkowników.

Dla pełnego rozwiązania potrzebowałem dostępu do własnego serwera. Korzystając z IIS7 dodałem nowy Web Site. Dodałem powiązania (Edit Bindings > Add) do goleszympansy.eu i www.goleszympansy.eu, dzięki czemu tylko żądania z tych adresów będą przekierowywane. Następnie w HTTP Redirect ustawiłem przekierowania do http://www.goleszympansy.pl, a typ przekierowania na 301 (permanent). Na końcu w Home ustawiłem jak docelowy adres IP mojego serwera, i gotowe.