Archives
April 2012 (1)
February 2012 (2)
December 2011 (3)
November 2011 (4)
October 2011 (2)
August 2011 (2)
July 2011 (1)
June 2011 (1)
May 2011 (5)
February 2011 (7)
January 2011 (4)
December 2010 (2)
October 2010 (8)
September 2010 (5)
Links
Tag Cloud
C#, Other, SharePoint

IISRESET bat file

Just create a txt file, rename is like ‘IISRESET.bat’.
In the bat file you type ‘IISRESET.exe’ and your done.
Easy and handy


Published: 4/2/2012 | 0  Comments | 0  Links to this post

After build command line …

When we build our DLL’s in Visual Studio we often want them to be transported to the GAC
and that an IISRESET is being executed
Use after build command lines in Visual Studio.

"C:\Program Files\Microsoft Visual Studio 9.0\SDK\v3.5\Bin\gacutil.exe" -u $(TargetName)

"C:\Program Files\Microsoft Visual Studio 9.0\SDK\v3.5\Bin\gacutil.exe" -i $(TargetFileName)

iisreset

 

 

C:\Program Files\Microsoft Visual Studio 9.0\SDK\v3.5\Bin\gacutil.exe ==> this is the path of you gacutil.

 

Hope it helps !


Published: 2/20/2012 | 0  Comments | 0  Links to this post

Generic CAML ….

Many times I find myself in the situation where I need to retrieve items
which need a more complex Caml query.
These procedures will give you a start Glimlach

 

public static string CreateCAMLQuery(string[] parameters, string fieldName, string type)
       {
           StringBuilder sb = new StringBuilder();

           //if (parameters.Length == 0)
           // AppendEQ(sb, "all");

           for (int i = 0; i < parameters.Length; i++)
           {
               AppendEQ(sb, parameters[i], fieldName, type);
               if (i > 0)
               {
                   sb.Insert(0, "");
                   sb.Append("");
               }
           }
           sb.Insert(0, "");
           sb.Append("");
           return sb.ToString();
       }
       private static void AppendEQ(StringBuilder sb, string value, string fieldName, string type)
       {
           // put your field's internal name in place of Category   
           sb.Append("");
           sb.Append(string.Format("", fieldName));
           sb.AppendFormat(string.Format("{1}", type, value));
           sb.Append("");
       }

I hope it helps !!!


Published: 2/16/2012 | 0  Comments | 0  Links to this post

Generic List of Objects to an XML = Serialization

Here is the code, it’s straight forward.

private string SerializeGenericList(List _list)
 {
 string _result = String.Empty;

 try
 {
 XmlSerializer ser = new XmlSerializer(_list.GetType());
 StringBuilder sb = new StringBuilder();
    using (StringWriter writer = new StringWriter(sb))
    {
       ser.Serialize(writer, _list);
      _result = sb.ToString();
      }
 }
 catch (Exception ex)
 {
 }
 return _result;
 }

                    
The function returns a string so we can easly create an XML.
Next thing you could is :

XmlDocument doc = new XmlDocument();
doc.LoadXml(SerializeGenericList(_list)); //_list is your Genereci List
 
Hope it helps !!!



Published: 12/22/2011 | 1  Comment | 0  Links to this post

SharePoint postback problem after file download

For a customer I was creating a project where they needed to click a button and download a file.
This is basic ASP.net stuff, BUT in SharePoint there are some issues with this.

If you use this code, which is the code to push a file towards the client browser for download:

Response.Clear();
Response.Buffer = true;
Response.BufferOutput = true;
Response.ContentType = "application/x-download";
Response.AddHeader("Content-Disposition", "attachment; filename=test.xml");
Response.CacheControl = "public";
Response.OutputStream.Write(buffer, 0, buffer.Length);
Response.Flush();

This code will work once,BUT next time you click the button it will not work.
Note: I’m using a byte array to publish, reason is that I created in this case an XML at runtime, this will be handled in an other blog

Solution:

We need to add Javascript to the button !!! Glimlach

 protected override void OnLoad(EventArgs e)
{
           public string ScriptRefresh =@"function Refresh()
                                        {
                                           window.setTimeout(
                                               function()
                                               {
                                                  _spFormOnSubmitCalled = false;
                                                }, 10);
                                           } ";  //This string represents the javascript fore this issue, it could be any kind of javascript.

this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(),"Refresh",ScriptRefresh, true);     //Here we add the Javascript to the page ,ScriptRefresh = javascript, you could type it directly here if you want
btnDownLoadXML.OnClientClick =
"Refresh()";  //Here we add the javascript to the button

}

Thats actually all you need to do.
What you are doing behind the scene is tell SharePoint that the page is not submitted yet.

Hope it helps


Published: 12/22/2011 | 0  Comments | 0  Links to this post

Beste way to remove HTML tags…

At a sudden moment you will come agross this issue.

You have an HTML stirng, ans all those tags should me removed.

There are severals ways to handle this issue,but this one solved my issue’s untill now:

 

return Regex.Replace(text, @”<(.|\n)*?>”, string.Empty);

 

Hope it helps you


Published: 12/5/2011 | 0  Comments | 0  Links to this post

Fill a content editor webparts ….

 
Some customers want to control all content in a list, and then read this list.
My list contains three columns:
  • Url: the realtive url of the page that contains the webpart.
  • HtmlContent: multiline filed that contains the html content.
  • Execute : boolean field, a check if we should update this page or not.
For I’ll do a query on this list to retrieve the pages that needed to be updated.
I also use resource class that contains all my values for my queries,fieldnames,listnames enz…
The code is pretty clear.
 
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
    try
    {
        if (properties.Feature.Parent is SPWeb)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {

                SPWeb web = (SPWeb)properties.Feature.Parent;

                if (GlobalProcedures.CheckList(ResourcesClass.Lists.Information.ListName))
                {
                    SPList _listInformation = web.Lists[ResourcesClass.Lists.Information.ListName];
                    SPQuery _query = new SPQuery { Query = ResourcesClass.Caml.Queries.RetrieveInformationExecute };
                    SPListItemCollection _listItemCollection = _listInformation.GetItems(_query);

                    foreach (SPListItem _infiormation in _listItemCollection)
                    {
                        string _url = _infiormation[ResourcesClass.Lists.Information.Fields.PageUrl].ToString();
                        string _htmlContent = _infiormation[ResourcesClass.Lists.Information.Fields.HtmlContent].ToString();

                        PublishingWeb _publishingWeb = PublishingWeb.GetPublishingWeb(web);
                        SPListItem _item = web.GetListItem(SPUrlUtility.CombineUrl(web.Url, _infiormation[ResourcesClass.Lists.Information.Fields.PageUrl].ToString()));

                        if (_item != null)
                        {
                            PublishingPage _publishingPage = PublishingPage.GetPublishingPage(_item);

                            if (_item.File.CheckOutStatus == SPFile.SPCheckOutStatus.None)
                            {
                                _publishingPage.CheckOut();
                            }
                            else
                            {
                                _item.File.UndoCheckOut();
                                _publishingPage.CheckOut();
                            }

                            using (SPLimitedWebPartManager _limitedWebPartManager = _item.File.GetLimitedWebPartManager(PersonalizationScope.Shared))
                            {
                                if (_limitedWebPartManager != null)
                                {
                                    foreach (System.Web.UI.WebControls.WebParts.WebPart _tmpWebPart in _limitedWebPartManager.WebParts)
                                    {
                                        try
                                        {
                                            if (_tmpWebPart.GetType().ToString().Equals(typeof(Microsoft.SharePoint.WebPartPages.ContentEditorWebPart).ToString()))
                                            {
                                                ContentEditorWebPart _contentEditorWebPart = (ContentEditorWebPart)_tmpWebPart;

                                                XmlDocument _xmlDocument = new XmlDocument();
                                                XmlElement _xmlElement = _xmlDocument.CreateElement("MyElement");
                                                _xmlElement.InnerText = _htmlContent;
                                                _contentEditorWebPart.Content = _xmlElement;
                                                //_contentEditorWebPart.Content = _xmlElement;


                                                _limitedWebPartManager.SaveChanges(_contentEditorWebPart);
                                                _publishingPage.CheckIn(String.Empty);

                                                if (_publishingWeb.PagesList.EnableModeration)
                                                {
                                                    _item.File.Publish(String.Empty);
                                                    _item.File.Approve(String.Empty);
                                                }
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            GlobalProcedures.WriteError(ex, "FeatureActivated");
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            });
        }
    }
    catch (Exception ex)
    {
        GlobalProcedures.WriteError(ex, "FeatureActivated");
    }

}
 
Good luck !

Published: 11/28/2011 | 0  Comments | 0  Links to this post

Properties.ListItem … be aware

When we write feature receivers we would like to use the following statement:

SPListItem _item =properties.ListItem;

This could cause problems regarding which context you’ll beloading.
Therefore use the following statement:

SPListItem _item =SPUrlUtility.CombineUrl(web.Url, properties.ListItem.Url);

 

Cheers


Published: 11/17/2011 | 0  Comments | 0  Links to this post

File to byte[] and back ….

 

Sometimes you need to put a file into a stirng or so.
Or you’ll find situations where you need to convert a string towards a byte[] array
and then convert this one to a file.

this code will put a file which can be a picture , pdf whatever into a byte[], then save this byte[] as a string.
If you should send this ‘string’ to somebody else and he ‘decompilles’ it back, he would eventually get your file.

using (FileStream _fileStream = new FileStream(_picturePath, FileMode.Open, FileAccess.Read))
                {
                    byte[] _arr = new byte[_fileStream.Length];
                    _fileStream.Read(_arr, 0, Convert.ToInt32(_fileStream.Length));
                    _arrGlobal = _arr;
                    txtOuput.Text = Convert.ToBase64String(_arrGlobal, 0, _arrGlobal.Length);
                }
The other way arround
string _outputPath = "your path here";
              byte[] _arrTemp = Convert.FromBase64String(txtOuput.Text);

              using (FileStream _fileStream = new FileStream(_outputPath, FileMode.Create))
              {
                  _fileStream.Write(_arrTemp, 0, _arrTemp.Length);
              }
 
These is a basic technique, but on the net there are many ways of doing it.
This one worked for me.
 
Hope it helps !

Published: 11/4/2011 | 0  Comments | 0  Links to this post

Sending email using Gmail

private static string sendMail(System.Net.Mail.MailMessage mm)
      {
          try
          {
              string smtpHost = "smtp.gmail.com";
              string userName = "[email protected]";//write your email address
              string password = "************";//write password
              System.Net.Mail.SmtpClient mClient = new System.Net.Mail.SmtpClient();
              mClient.Port = 587;
              mClient.EnableSsl = true;
              mClient.UseDefaultCredentials = false;
              mClient.Credentials = new NetworkCredential(userName, password);
              mClient.Host = smtpHost;
              mClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
              mClient.Send(mm);
          }
          catch (Exception ex)
          {
              System.Console.Write(ex.Message);
          }

          return "Send Sucessfully";
      }

Published: 11/4/2011 | 0  Comments | 0  Links to this post
 Next >>