lamp
Find duplicate bookmarks in chrome, and delete Dead links
26 July 10 10:08 PM | Frederick.Chapleau | with no comments

A great Google Chrome Extension that can find duplicate bookmarks, and search for dead links... if you want to access it, check out the options in the extension itself, in the Chrome Extensions page...

Bookmark Sentry
https://chrome.google.com/extensions/detail/bdglbbcbmgnimogcmcdenggkpdmihlga

-f.

Filed under:
Screen Capture and Save to File
25 July 10 10:30 PM | Frederick.Chapleau | with no comments

A little code snippet that is doing a Screen Capture, saving it to a Jpeg file, and launch the default program associated to jpg to view it.

Size s = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Size;
string filename = Path.GetTempFileName() + ".jpg";
using (Bitmap bitmap = new Bitmap(s.Width, s.Height))
{
    using (Graphics g = Graphics.FromImage(bitmap))
    {
        g.CopyFromScreen(new Point(0, 0), new Point(0, 0), s);
    }
    bitmap.Save(filename, ImageFormat.Jpeg);
}

Process.Start(filename);

-f.

Filed under:
ServiceHost only supports class service types.
16 July 10 04:37 PM | Frederick.Chapleau | with no comments

In WCF, ServiceHost instantiate the class that your Service inherit, when you access the .svc file, which is not the interface, but the class itself.

Check out the .svc file (open it with the XML or Text Editor) and validate that the inherited class is the good one.

-f.

Filed under:
Start a process and follow the output in C#
11 July 10 05:56 PM | Frederick.Chapleau | with no comments

ProcessStartInfo psi = new ProcessStartInfo(@"c:\windows\system32\ping.exe");
psi.Arguments = "127.0.0.1";
psi.RedirectStandardOutput = true;
psi.UseShellExecute = false;

Process process = Process.Start(psi);
process.WaitForExit();
string output = process.StandardOutput.ReadToEnd();
process.Dispose();

Console.WriteLine(output);
Console.ReadKey();

Filed under:
Google Reader API to check for Unread Article
09 July 10 04:26 PM | Frederick.Chapleau | with no comments

Everything you need to have a summary of unread item in your Google Reader account…!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Xml;

namespace Chapleau.GoogleReader
{
    public class GoogleReader
    {
        private string _sid = null;
        private string _token = null;
        private string _auth = null;
        private Cookie _cookie = null;

        private string _username;
        private string _password;

        public GoogleReader(string username, string password)
        {
            _username = username;
            _password = password;

            connect();
        }

        private bool connect()
        {
            getToken();
            return _token != null;
        }
        private void getToken()
        {
            getSid();
            _cookie = new Cookie("SID", _sid, "/", ".google.com");

            string url = "http://www.google.com/reader/api/0/token";

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "GET";
            req.CookieContainer = new CookieContainer();
            req.CookieContainer.Add(_cookie);
            req.Headers.Add("Authorization", "GoogleLogin auth=" + _auth);

            HttpWebResponse response = (HttpWebResponse)req.GetResponse();
            using (var stream = response.GetResponseStream())
            {
                StreamReader r = new StreamReader(stream);
                _token = r.ReadToEnd();
            }
        }
        private void getSid()
        {
            string requestUrl = string.Format
                ("https://www.google.com/accounts/ClientLogin?service=reader&Email={0}&Passwd={1}",
                _username, _password);
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(requestUrl);
            req.Method = "GET";

            HttpWebResponse response = (HttpWebResponse)req.GetResponse();
            using (var stream = response.GetResponseStream())
            {
                StreamReader r = new StreamReader(stream);
                string resp = r.ReadToEnd();

                foreach (string cLine in resp.Split('\n'))
                {
                    if (cLine.StartsWith("SID=")) { _sid = cLine.Replace("SID=", ""); }
                    //if (cLine.StartsWith("LSID=")) { cLSID = cLine.Replace("LSID=", ""); }
                    if (cLine.StartsWith("Auth=")) { _auth = cLine.Replace("Auth=", ""); }
                }
            }
        }

        private HttpWebResponse httpGet(string requestUrl, string getArgs)
        {
            string url = string.Format("{0}?{1}", requestUrl, getArgs);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.CookieContainer = new CookieContainer();
            request.CookieContainer.Add(_cookie);
            request.Headers.Add("Authorization", "GoogleLogin auth=" + _auth);

            try
            {
                return (HttpWebResponse)request.GetResponse();
            }
            catch
            {
                // handle error
                return null;
            }
        }

        private HttpWebResponse httpPost(string requestUrl, string postArgs)
        {
            byte[] buffer = Encoding.GetEncoding(1252).GetBytes(postArgs);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUrl);
            request.Method = "POST";
            request.CookieContainer = new CookieContainer();
            request.CookieContainer.Add(_cookie);
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = buffer.Length;

            Stream PostData = request.GetRequestStream();

            PostData.Write(buffer, 0, buffer.Length);
            PostData.Close();

            try
            {
                return (HttpWebResponse)request.GetResponse();
            }
            catch
            {
                //handle error
                return null;
            }
        }

        public int GetUnreadCount(out string details, out int numberOfFeed)
        {
            StreamReader r = new StreamReader(httpGet("http://www.google.com/reader/api/0/unread-count", "all=true&output=xml").GetResponseStream());
            string c = r.ReadToEnd();
            r.Close();

            XmlDocument d = new XmlDocument();
            d.LoadXml(c);

            details = string.Empty;
            int count = d.DocumentElement.SelectNodes("/object/list/object").Count;
            if(count > 0)
                count = count - 1;
            numberOfFeed = count;

            foreach(XmlElement e in d.DocumentElement.SelectNodes("/object/list/object"))
            {
                XmlElement nameNode = (XmlElement)e.SelectSingleNode("string[@name='id']");

                if (nameNode.InnerText.Contains("reading-list"))
                {
                    return int.Parse(e.SelectSingleNode("number[@name='count']").InnerText);
                }
                else
                {
                    details += e.SelectSingleNode("number[@name='count']").InnerText + " @ " + e.SelectSingleNode("string[@name='id']").InnerText + Environment.NewLine;
                }

            }
            return 0;
        }
    }
}

Filed under:
The Best Generic-Lazy-Initialized Singleton implementation
01 July 10 09:23 AM | Frederick.Chapleau | with no comments

public abstract class Singleton<T>
    where T: class, new()
{
    public static T Instance
    {
        get { return Nested.instance; }
    }

    private class Nested
    {
        // Explicit static constructor to tell C# compiler
        // not to mark type as beforefieldinit
        static Nested() { }

        internal static readonly T instance = new T();
    }
}

public sealed class MyType : Singleton<MyType>
{
}

ref. :  http://stackoverflow.com/questions/953259/an-obvious-singleton-implementation-for-net/953441#953441

also http://stackoverflow.com/questions/610818/what-does-beforefieldinit-flag-do

Filed under:
WCF Error : The token provider cannot get tokens for target
30 June 10 12:17 PM | Frederick.Chapleau | with no comments

The inner exception is a much better source for this error message. The underlying message was

The NetworkCredentials provided were unable to create a Kerberos credential, see inner execption for details.

And from this exception the inner one’s detail was

InitializeSecurityContent failed. Ensure the service principal name is correct.

Adding clientCredentialType="None" solve this problem… by default it’s not None, but “Windows” which is relying on Kerberos.

<message clientCredentialType="None" negotiateServiceCredential="false" establishSecurityContext="false" />

Then,  I had the problem

The service certificate is not provided for target 'http://localhost:10000/Service1.svc'. Specify a service certificate in ClientCredentials.

So I found this post on StackOverflow and remove everything under security to add only the mode to the security node to None.

<security mode="None"/>

Filed under:
Download .NET Framework 4.0 – Direct Link
20 April 10 11:18 AM | Frederick.Chapleau | with no comments

http://www.microsoft.com/downloads/details.aspx?FamilyID=9cfb2d51-5ff4-4491-b0e5-b386f32c0992&displaylang=en

It took me too long to find it (almost… 20 sec). I hope Google will index that first ;)

-f.

Filed under:
Relay Permission on Exchange 2010
13 April 10 04:59 PM | Frederick.Chapleau | with no comments

What can I say more…

Get-ReceiveConnector "The Connector Name" | Add-ADPermission -User "NT AUTHORITY\ANONYMOUS LOGON" -ExtendedRights "ms-Exch-SMTP-Accept-Any-Recipient"

-f.

Filed under:
Visual Studio setup cannot run in compatibility mode in VS2010
13 April 10 09:56 AM | Frederick.Chapleau | 1 comment(s)

The solution from Dluk, posted for the Beta2 Version of Visual Studio 2010 on 11/10/2009 and worked for me with the **released** version was…:

Got it!
1. Rename following registry key before install (e.g. add _ to the name):
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\setup.exe\HighVersionLie-{6B64DE21-0F4C-4479-9D6C-0FBCA496BCDC}
2. Install VS2010
3. Return key name back.

-f.

ref.: https://connect.microsoft.com/VisualStudio/feedback/details/499921/beta2-failed-to-start-installation-visual-studio-setup-cannot-run-in-compatibility-mode

Filed under:
Underscore prefix with C#, is it a best practice?
01 March 10 01:52 PM | Frederick.Chapleau | with no comments

I used this since the beginning, thinking that this was a best practice, but without searching a lot.

I found this article containing a brief history on this practice... I’ll let you decide if it’s a best practice to you.

http://blogs.msdn.com/sourceanalysis/archive/2008/05/25/a-difference-of-style.aspx

-f.

Filed under:
Atlasian: Really, really great, and almost FREE!
19 February 10 11:04 AM | Frederick.Chapleau | with no comments

10$ for Each of :

JIRA : The best Issue Tracker

Confluence : The best Wiki/Blog engine

… and many others!

http://www.atlassian.com/starter/

-f.

Filed under:
Get the Unread count of the Inbox of Exchange 2010/2007, using web services
02 February 10 09:28 AM | Frederick.Chapleau | with no comments

I searched a lot and, based on an article from SANDEEP APARAJIT, I was able to query for unread email from my Exchange mailbox inbox, in about 15 min. Thanks!

 

ServicePointManager.ServerCertificateValidationCallback = delegate(Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; };

ExchangeServiceBinding service = new ExchangeServiceBinding ();

service.RequestServerVersionValue = new RequestServerVersion();
service.RequestServerVersionValue.Version = ExchangeVersionType.Exchange2010;
service.EnableDecompression = true;
service.Credentials = new NetworkCredential("username", "password", "domain");
service.Url = @https://exchangeserver/EWS/exchange.asmx;

int merCurrentCount = GetUnreadFolderItemsCount(service, "Inbox");

… and the functions…

public int GetUnreadFolderItemsCount(ExchangeServiceBinding service, string folderName)
       {
           int unReadCount = -1;
           // Identify the folder properties to return.
           FolderResponseShapeType properties = new FolderResponseShapeType();
           PathToUnindexedFieldType ptuft = new PathToUnindexedFieldType();
           ptuft.FieldURI = UnindexedFieldURIType.folderManagedFolderInformation;
           PathToUnindexedFieldType[] ptufts = new PathToUnindexedFieldType[1] { ptuft };
           properties.AdditionalProperties = ptufts;
           properties.BaseShape = DefaultShapeNamesType.AllProperties;

           // Form the get folder request.
           BaseFolderIdType p_folder = FindFolderID(service, folderName);

           GetFolderType request = new GetFolderType();
           request.FolderIds = new BaseFolderIdType[1] { p_folder };
           request.FolderShape = properties;

           // Send the request and get the response.
           GetFolderResponseType response = service.GetFolder(request);

           ArrayOfResponseMessagesType aormt = response.ResponseMessages;
           ResponseMessageType[] rmta = aormt.Items;
           foreach (ResponseMessageType rmt in rmta)
           {
               if (rmt.ResponseClass == ResponseClassType.Error)
               {
                   throw new Exception(rmt.MessageText);
               }
               else
               {
                   FolderInfoResponseMessageType firmt;
                   firmt = (rmt as FolderInfoResponseMessageType);
                   BaseFolderType[] folders = firmt.Folders;

                   foreach (BaseFolderType rfolder in folders)
                   {
                       if (rfolder is FolderType)
                       {
                           FolderType myFolder;
                           myFolder = (rfolder as FolderType);
                           if (myFolder.UnreadCountSpecified)
                           {
                               unReadCount = myFolder.UnreadCount;
                           }
                       }
                   }
               }
           }
           return unReadCount;
       }

       public static FolderIdType FindFolderID(ExchangeServiceBinding service, String folderName)
       {
           DistinguishedFolderIdType objSearchRootFolder = new DistinguishedFolderIdType();
           objSearchRootFolder.Id = DistinguishedFolderIdNameType.msgfolderroot;

           FindFolderType requestFindFolder = new FindFolderType();
           requestFindFolder.Traversal = FolderQueryTraversalType.Deep;
           requestFindFolder.ParentFolderIds = new DistinguishedFolderIdType[] { objSearchRootFolder };
           requestFindFolder.FolderShape = new FolderResponseShapeType();
           requestFindFolder.FolderShape.BaseShape = DefaultShapeNamesType.IdOnly;

           //Search filter definition
           requestFindFolder.Restriction = new RestrictionType();

           #region Contains expression

           ContainsExpressionType objContainsExpression = new ContainsExpressionType();
           objContainsExpression.ContainmentMode = ContainmentModeType.FullString;
           objContainsExpression.ContainmentModeSpecified = true;
           objContainsExpression.ContainmentComparison = ContainmentComparisonType.Exact;
           objContainsExpression.ContainmentComparisonSpecified = true;

           PathToUnindexedFieldType objFieldFolderName = new PathToUnindexedFieldType();
           objFieldFolderName.FieldURI = UnindexedFieldURIType.folderDisplayName;
           objContainsExpression.Item = objFieldFolderName;

           objContainsExpression.Constant = new ConstantValueType();
           objContainsExpression.Constant.Value = folderName;

           #endregion Contains expression

           requestFindFolder.Restriction.Item = objContainsExpression;

           FindFolderResponseType objFindFolderResponse =
               service.FindFolder(requestFindFolder);

           if (objFindFolderResponse.ResponseMessages.Items.Length == 0)
               return null;

           foreach (ResponseMessageType responseMsg in
               objFindFolderResponse.ResponseMessages.Items)
           {
               if (responseMsg.ResponseClass == ResponseClassType.Success)
               {
                   FindFolderResponseMessageType objFindResponse =
                       responseMsg as FindFolderResponseMessageType;
                   foreach (
                       BaseFolderType objFolderType in objFindResponse.RootFolder.Folders)
                   {
                       return objFolderType.FolderId;
                   }
               }
           }
           return null;
       }

-f.

Filed under:
SSL for FREE
15 January 10 09:45 AM | Frederick.Chapleau | with no comments

Yes, we can now secure servers using free certificates :)

http://StartSSL.com

-f.

Filed under:
The registry on a 64bits OS using NSIS
13 January 10 08:10 PM | Frederick.Chapleau | with no comments

Ok, after trying to find a patch or a work around to access the write 64 bit registry node instead of the Wow6432Node, I found a … not very documented but simple way to do it...

${If} ${RunningX64}
     SetRegView 64
${EndIf}

-f.

Filed under:
More Posts Next page »