Thread Safe Invoke Functions

Download Project
Every developer who using threads  encounter with Illegal Cross Thread operations. And they solve this probles with creating delegate functions and invoking by other control. And this action cause writting more code. In this post i introduce you  an InvokeService classes that using methods with threadsafe operations.

Before this we make a method thread safe like this and think about all methods you do it like this way it causes lots of codes:

       //This code is not nessasary now
        public delegate void AppendTextDelegate(string text);
        public void GetSomeOutsiteData(string data)
        {
            this.Invoke(new AppendTextDelegate(AppendText), data);
        }
        //The method that use for thread safe
        public void AppendText(string text)
        {
            textBox1.Text += text + Environment.NewLine;
        }

Now just one line:

Instance.RegisterThreadSafeWatcher("AppendText", this,(Delegatenew Server.DataRecievedDelegate(AppendText));

Usage :

“Test” Class
First you create a business class that  inherits  form “InvokableBase”.And two sample delegate method that used by this class.Also this class contains a different thread for doing its jobs will cause “Cross Thread operation”.For doing this we use Invoke() function of  base class of InvokableBase

    class Test:InvokableBase,IDisposable
    {
        public delegate void TextDelegate(string text);
        public delegate void IntDelegate(int text);
        Thread a = null;
        public void DoSomething()
        {
           a = new Thread(new ThreadStart(worker));
            a.Start();
        }
        public void worker()
        {
            for (int i = 0; i < 10; i++)
            {
                string text = "Hello World";
                base.Invoke(typeof(TextDelegate), text);
                Thread.Sleep(1000);
            }
            for (int i = 0; i < 10; i++)
            {
                base.Invoke(typeof(IntDelegate), i);
                Thread.Sleep(1000);
            }
        }

A Windows Form Class This class can used by main thread for complete its GUI operations. Test class sends text and integer data to this form class and this forms safely prints it into a multiline textbox and using InvokeService prevents errors of cross thread operations.

        Test cls =null;
        private void button1_Click(object sender, EventArgs e)
        {
            cls = new Test();
            cls.RegisterThreadSafeWatcher("AppendText", this,(Delegate) new Test.TextDelegate(AppendText));
            cls.RegisterThreadSafeWatcher("AppendInt", this, (Delegate) new Test.IntDelegate(AppendInt));
            cls.DoSomething();
        }
        public void AppendText(string value)
        {
            textBox1.Text += value + Environment.NewLine;
        }
        public void AppendInt(int value)
        {
            textBox1.Text += value.ToString() + Environment.NewLine;
        }
        private void TestForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            cls.Dispose();
        }
You can download full project from this link:
http://rapidshare.com/files/308290393/InvokeService.rar
Have a nice coding !

Remove last character using TrimEnd()

You somehow create  an array using a loop  and want to sperate items with comma or etc. but everyone knows the last char of this array is one of that comma and unwant.You have to remove it. Usually we do this like

string mystring = “some,thing,in,this,array,”;

   mystring = mystring.Substring(0, mystring.Length - 1);

this is correct bu there is an easy way to do it:

   mystring = mystring.TrimEnd(',');

Disable caching in an HttpHandler

Disable caching in an HttpHandler ,Use this:

context.Response.Clear();
context.Response.Cache.SetCacheability(HttpCacheability.Public);
context.Response.Cache.SetExpires(DateTime.MinValue);

Sharepoint Email Alerts not working

You can use this stsadm commands to stop start alerts its worked for me

stsadm.exe -o setproperty -url http://intranet -pn alerts-enabled -pv true

stsadm.exe -o setproperty -url http://intranet -pn job-immediate-alerts -pv "every 5 minutes"

Error while starting the Full Crawl

Got this error while starting the full crawl on Local Office Sharepoint Server Sites (default content source)

The resolution for this was to add the following registry key

1) Click Start, click Run, type regedit, and then click OK.
2) In Registry Editor, locate and then click the following registry key:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa
3) Right-click Lsa, point to New, and then click DWORD Value.
4) Type DisableLoopbackCheck, and then press ENTER.
5) Right-click DisableLoopbackCheck, and then click Modify.
6) In the Value data box, type 1, and then click OK.
7) Quit Registry Editor, and then restart your computer.

How to disable loopback check:
http://support.microsoft.com/kb/896861

Sharepoint stop caching xml or media files

If  you are using sharepoint you noticed that every xml,img or media files are cached automatically. This is good for performance but its so problematic for changes or updates. You change something in your xml at background but users can not see changes because of sharepoint caching .

Solution is so easy

this is your file path:

[your xml url]/myfile.xml
[your img url]/img.jpg

if you change it like this

[your xml url]/myfile.xml?ver=[some number]

[your img url]/img.jpg?ver=[some number]

and after change your xml content generate some random number for [some number] sharepoint relaese caching your media or data files.I am using GUID for this 🙂

Getting Root Site in Sharepoint

When you are working in sharepoint with extended web applications which is using different authentication methods . You have to need current URL of different domain for hardcoded envoriment . For example http://www.test.com one of your extranet using forms authentication and http://myserver is your default and using windows authentication. if user create a request from http://www.test.com/somedifferet&#8230; you need to root of http://www.test.com rather than http://myserver.And you dont want a login screen because of links.

if you type hard code like this its not working for default domain which image not in _layout folder.

<img src=”http://myserver/something/imagenotcomingfromlayout.jpg”&gt; asks extra windows auth login

Solution.

<img src=”/_layouts/GetRootSite.ashx?url=http://myserver/something/imagenotcomingfromlayout.jpg”>

Handlers returns same as users coming request root site.and change http://myserver/ to http://www.test.com

Create a generic handler like below and add this handler to 12/TEMPLATES/LAYOUTS folder for every registered user can reach.

<%@ WebHandler Language=“C#” Class=“GetRootSite” %>

using System;

using System.Web;

using System.Net;


public
class GetRootSite : IHttpHandler

{

public void ProcessRequest (HttpContext context) {

Uri requestUri = context.Request.Url;

string baseUrl2 = context.Request.Url.GetLeftPart(UriPartial.Authority);

string gelenpath = context.Request.QueryString[“url”];

Uri gelen = new Uri(gelenpath);

string gelenPreFix = gelen.GetLeftPart(UriPartial.Authority);

string artakalan = gelenpath.Substring(gelenPreFix.Length);

string sonuc = baseUrl2 + artakalan;

context.Response.Redirect(sonuc);

}

public bool IsReusable {

get {

return false;

}

}

}