Thursday, 8 March 2012

Usuwanie niechcianych folderów z dysku

Nie znoszę, kiedy system operacyjny próbuje za mnie decydować, co jest dla mnie najlepsze. A już w szczególności, kiedy odmawia mi uprawnień do katalogów i plików na moim dysku!
Podobny probem opisywałem przy okazji katalogu windows.old, ale tym razem rozwiązanie nie było tak proste.

Po jakiejś instalacji pozostał mi na dysku twardym katalog o długiej nazwie, i za nic nie chce się dać usunąć. W dodatku zawiera tylko pliki EULA w kilkudziesięciu językach. Te pliki nie wskazują co prawda, który dokładnie program je zostawił, ale pojawia się nazwa Microsoftu.

Pierwsza próba usunięcia katalogu po dobroci się nie udaje:

Sprawdzam właściwości katalogu, idę do karty Zabezpieczenia. Klikam "Zaawansowane".

OK, niby jako należący do grupy Administratorzy, powinienem mieć uprawnienia do zmiany katalogu wraz z zawartością (w tym do usuwania). Więc dlaczego nie mogę go usunąć?
Próbuję zmienić uprawnienia. Nie jest to możliwe, dostaję w twarz komunikatem o błędzie.

To inaczej. Przechodzę na kartę Właściciel. Właścicielem jest SYSTEM. Zmieniam go na aktualnego użytkownika. Zmienione. Sprawdzam, czy mogę usunąć katalog. Niestety, tym razem muszę uzyskać uprawnienia od samego siebie.

Usuwam SYSTEM z listy uprawnionych użytkowników. Znów odmowa dostępu. Mimo to SYSTEM znika, zostaję tylko ja. Kolejna próba usunięcia. Efekt - najwyraźniej mam już uprawnienia do katalogu, ale nie do plików w środku.

Kolejna próba zmiany właściwości plików wewnątrz katalogu kończy się niedającym się zamknąć oknem dialogowym. Grzecznie kończę Task Managerem proces explorer.exe i uruchamiam go ponownie.

W końcu odnalazłem odpowiednie ustawienia. Po tym, jak już zmieniłem właściciela katalogu (dla podkatalogów również) i pozostał tylko jeden użytkownik w zaawansowanych ustawieniach zabezpieczeń, należało kliknąć na uprawnienia Administratorów, wybrać "Edytuj" i w kolejnym oknie zaznaczyć najlepiej wszystkie uprawnienia (w tym do usuwania). Co ważne, należało również zaznaczyć pole o zastąpieniu ustawień obiektów podrzędnych.

Teraz mogłem wreszcie usunąć katalog.


Podsumowując:
1.       Zmień właściciela obiektu, i koniecznie zaznacz aby zmieniony był również dla "podkontentów i obiektów".
2.       Usuń niepotrzebnych użytkowników, takich jak SYSTEM
3.       Zmień uprawnienia ustawiając sobie pełną kontrolę i koniecznie zaznacz, aby uprawnienia obiektów podrzędnych były dziedziczone.

Powyższe kroki pozwolą odzyskać kontrolę nad katalogiem.

Wednesday, 7 March 2012

Telerik Upload control file types

I use Telerik's RadUpload control in my SharePoint project. That's why I don't define Upload control in ASPX file, but I do this from code-behind instead.

In this scenario I use RadDialogOpener class. Then I add DialogDefinition, and set FileManagerDialogParameters.
RadDialogOpener DialogOpener1;
DialogOpener1 = new RadDialogOpener();
FileManagerDialogParameters fmdp = new FileManagerDialogParameters();
fmdp.FileBrowserContentProviderTypeName = typeof(SharepointTelerikCustomProvider).AssemblyQualifiedName;
DialogDefinition mediaManager = new DialogDefinition(typeof(MediaManagerDialog), fmdp);
DialogOpener1.DialogDefinitions.Add("MediaManager", mediaManager);
The effect looks like this:
Recently I needed to create two different fields, one for uploading video, other for audio. Question is, how to change default file types of MediaManagerDialog?
I set SearchPatterns property:
fmdp.SearchPatterns = new string[] { "*.wma", "*.wav", "*.mp3", "*.m3u", "*.mid", "*.midi", "*.snd" };
for audio control and
fmdp.SearchPatterns = new string[] { "*.wmv", "*.avi", "*.mpeg", "*.mpg", "*.mpe", "*.mkv" };
for video.

Watch out for proper format: asterisk-dot-extension. Otherwise you get InvalidFileExtension message.

Tuesday, 7 February 2012

Multiple addresses in MailMessage.To Property

Sending e-mail is easy with System.Net.Mail.MailMessage class. Unfortunately, MSDN example only shows how to send e-mail to one recipient. It is possible to send email to multiple recipients, but what is the delimiter?

From my tests I found out, that accepted delimiter is comma or comma-and-space. Semicolon without space will cause FormatException.
This small program will try sending e-mails with different delimiters. Let’s see what happens:
string from = "test@goleszympansy.pl";
string[] tos = {"one@goleszympansy.pl, two@goleszympansy.pl",
                "one@goleszympansy.pl,two@goleszympansy.pl",
                "one@goleszympansy.pl; two@goleszympansy.pl",
                "one@goleszympansy.pl;two@goleszympansy.pl"};
string subject = "Test mail";
string body = "GoleSzympansy";
string host = GetHost();

foreach (var to in tos)
{
    try
    {
        SmtpClient smtpClient = new SmtpClient();
        smtpClient.Host = host;
        MailMessage mailMessage = new MailMessage(from, to, subject, body);
        smtpClient.Send(mailMessage);
        Console.WriteLine("Mail send success: {0}", to);
    }
    catch
    {
        Console.WriteLine("Mail send failed: {0}", to);
    }
}
And this is a result:

So  at first it seemed, that semicolon-and-space would also be valid delimiter. But what would be actually be received?
In the third case ("one@goleszympansy.pl;  two@goleszympansy.pl"), the first part before space, together with semicolon, is considered to be recipient's name:

Summing up:
If you want to add more addresses, divide them by comma. And the space will divide display name and email address. The "To" property accepts following formats:
  • "email@server.com"
  • "email1@server1.com,  email2@server2.com"
  • "Name email@server.com"
  • "name email@server1.com, email@server2.com"
etc...

Monday, 30 January 2012

Internet access under VPN

Sometimes, when you are connected to VPN you suddenly loose access to Internet. Or you may notice, that suddenly you don't have access to some websites.
This is because when you're connected to another network, your computer is trying to use that network's internet access. And if this is company network, proxy servers may block certain websites, or your employer may log all your browsing history.
To change this, you need to change your computer's gateway. 

1. Open VPN connection, go to "Networking" and click "Properties"

2. Click "Advanced"

3. Uncheck "Use default gateway on remote network".

4. Reconnect.
Now you're using your local network to connect to Internet. To test it, just google "My IP" and see how your address changes.

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.