Wednesday, December 19, 2012

How to run PowerShell script

Because my memory is not the best knowledge base, I do not memorize things I do just once or twice per half a year :)
Because of this reason I got this error message from PowerShell whenever I tried to run some scripts:


The term 'test.ps1' is not recognized as a cmdlet, function, operable program, or script file. Verify the term and try again.
At line:1 char:7
+ test.ps1 <<<<
That is why I decided to cover this error message for me once and for all  :)
Article below describe it very well.

http://technet.microsoft.com/en-us/library/ee176949.aspx

Thursday, November 1, 2012

List of all SharePoint users

Hi everyone,
Coincidentally I have found out that SharePoint has list with all user. Even though this list is hidden (as Workflow history list is) you can still access it if you have administrators rights. You just use your server name and add this /_catalogs/users/simple.aspx.

Example:
https://myspserver.com/_catalogs/users/simple.aspx

This list stores some data about SharePoint users and you are able to access it through code as well. I don't want to rewrite what have been already written so I am gonna point you to this wonderful site :) http://zimmergren.net/technical/sharepoints-hidden-user-list-user-information-list here you will be able to read more about this list ;)

Thanks for reading...

Tuesday, October 16, 2012

How to connect to ORACLE database using C#

Hi everyone,
Even though this topic is not directly connected with SharePoint, you may need or one day you will need :) to connect to the Oracle DB. Although it is not difficult task, this sample could help you to avoid some hassle with data mining from Oracle DB. (It helped me :) ) I am sure there are other approaches to do so and as always if you now better one I will be glad to know them :)
So lets start with sample. Basically you will need just one class which encapsulate whole connection and returns some data type you may need.


class OracleConnectionClass
    {
        private OracleConnection _conn;

        #region PossibleErrors
        //  Some possible errors
        //   System.Data.OracleClient requires Oracle client software version 8.1.7 or greater
        //     If this is encountered it could be a permission problem accessing the location 
        //     where the oracle dlls are…but most likely the dlls are not in the same directory as the executable or found within the environment path of the system.

        //   ORA-12541: TNS:no listener
        //   This one could mean that one of the connection settings is incorrect and the database could not be connected to 
        //   and this generic error comes back. Try tweaking the settings, port, instance 
        #endregion 

        #region STATIC
        /// <summary>
        /// creates connection to DB
        /// </summary>
        /// <returns>ElanorADOracleConnection to GLOBUSAD</returns>
        public static OracleConnectionClass GetTestDBconnection()
        {
            string connectionString = "Data Source=(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP)(HOST = SERVER_URL)(PORT = PORT_NUMBER))(CONNECT_DATA = (SID = YOUR_SID)));User Id=USER_NAME;Password=USER_PASSWORD;";
            return new OracleConnectionClass(connectionString);
        }
        #endregion

        #region CONSTRUCTORS
        /// <summary>
        /// Creates and open connection
        /// </summary>
        /// <param name="connString"></param>
        public OracleConnectionClass(string connString)
        {
            try
            {
                _conn = new OracleConnection(connString);
                _conn.Open();
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }

        #endregion

        /// <summary>
        /// Gets state of connection
        /// </summary>
        public ConnectionState State
        {
            get
            {
                return this._conn.State;
            }
        }

        /// <summary>
        /// Closes and disposes the connection
        /// </summary>
        public void Close()
        {
            if (_conn != null)
            {
                _conn.Close();
                _conn.Dispose();
                _conn = null;
            }
        }

        /// <summary>
        /// gets list of Int32 values
        /// </summary>
        /// <param name="SQLString">sql query string</param>
        /// <returns>ArrayList of string's Int32 values </returns>
        public ArrayList GetInt32ValuesArray(string SQLString)
        {
            ArrayList a = new ArrayList();
            OracleCommand cmd = new OracleCommand(SQLString, this._conn);
            OracleDataReader reader = cmd.ExecuteReader();

            while (reader.Read())
            {
                a.Add(Convert.ToString(reader.GetInt32(0)));
            }
            reader.Close();
            reader.Dispose();
            cmd.Dispose();
            return a;
        }

        /// <summary>
        /// gets string value from db
        /// </summary>
        /// <param name="sql">sql query string</param>
        /// <returns>returns string value of the first column of the first row</returns>
        public string GetValue(string sql)
        {
            string retValue;
            OracleCommand command = new OracleCommand(sql, this._conn);
            try
            {

                retValue = command.ExecuteScalar().ToString();
            }
            catch (NullReferenceException)
            {
                retValue = String.Empty;
            }
            command.Dispose();

            return retValue;
        }

        /// <summary>
        /// gets data reader
        /// </summary>
        /// <param name="sql">sql query string</param>
        /// <returns>OracleDataReader </returns>
        public OracleDataReader GetDataReader(string sql)
        {
            OracleCommand cmd = new OracleCommand(sql, this._conn);
            return cmd.ExecuteReader();
        }

        /// <summary>
        /// gets disconnected data table
        /// </summary>
        /// <param name="sql">sql query string</param>
        /// <returns>disconected DataTable</returns>
        public DataTable GetTable(string sql)
        {
            OracleCommand command = new OracleCommand(sql, this._conn);
            OracleDataAdapter da = new OracleDataAdapter();
            DataTable dt = new DataTable();
            da.SelectCommand = command;
            da.Fill(dt);
            da.Dispose();
            da = null;
            return dt;
        }
    }

I guess that code is quite understandable. Important thing is to set correct connection in "GetTestDBconnection" function. You can also create more functions to get data from various databases. The rest can remain in peace if you are willing to :)
And below is the way how to use this class to actually get some data:


    class Program
    {
        static void Main(string[] args)
        {
                //Create variable
                OracleConnectionClass oracleConnection = null;
                //Initialize it
                oracleConnection = OracleConnectionClass.GetTestDBconnection();
                
                //Create datatable
                DataTable oracleDataTable;
                
                //Get data from DB
                oracleDataTable = oracleConnection.GetTable("SELECT * FROM OracleDB");
                
                //Close connection
                oracleConnection.Close();
        }
    }


Ok then, that should be all. If you would find anything unclear or wrong, do not hesitate to let me know ;)
Happy codding.


Friday, September 7, 2012

How to delete all items in SharePoint list


If you would need to delete all items in SharePoint list you can't just use foreach loop on the list and delete each item. There is the simple way how to achieve this which I found:


using (SPSite site = new SPSite("https://Your_server/Your_site"))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPList list = web.Lists["ListItem"];
                        Hashtable itemsToDelete = new Hashtable(list.ItemCount);
                        foreach (SPListItem item in list.Items)
                        {
                            itemsToDelete.Add(item.ID, null);
                            Console.Write("+");
                        }

                        Console.WriteLine("---------------------------");
                        Console.WriteLine("---------------------------");

                        foreach (int ID in itemsToDelete.Keys)
                        {
                            list.Items.DeleteItemById(ID);
                            Console.Write("|" + ID + "|");
                        }

                        itemsToDelete.Clear();
                        Console.WriteLine("Items were deleted.");
                    }
                }

Happy coding...

Friday, August 17, 2012

How to convert string to DateTime

Hi everybody,
just because I need store more knowledge than my brain can handle it I am posting about this :) And maybe someone finds it useful too....

If you receive the date as a string, you have to parse it to the DateTime. After that you can do all magic things which are not available for the string :)

//Received string
string dateString = "2.7.2012  13:55:07";
//To prevent differences between time zone you have to specify culture info
IFormatProvider theCultureInfo = new System.Globalization.CultureInfo("cs-CZ", true);

//Parsing time :)
DateTime dateDateTime= DateTime.ParseExact(myDate, "d.M.yyyy  HH:mm:ss", theCultureInfo);
//Now you can look what you did...
Console.WriteLine(dateDateTime.ToString("dd-MM-yyyy HH:mm"));

The list of culture info is here: http://www.csharp-examples.net/culture-names/

And little bit about SharePoint.
Because SharePoint DateTime conforms to ISO 8601 you don't need to use ParseExact method and you will be able to use just DateTime.Parse method. Also when you need to fill DateTime field in SP, this source code might be a helpful for you:
DateTime nowDate = DateTime.Now;
string spFormat = Microsoft.SharePoint.Utilities.SPUtility.CreateISO8601DateTimeFromSystemDateTime(nowDate);

Happy coding :)

Tuesday, July 17, 2012

Verify user credentials

If you would need to verify user's windows credentials you can use this code:
            // create a "principal context" - e.g. your domain (could be machine, too)
            using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, "DOMAIN"))
            {
                // validate the credentials
                bool isValid = pc.ValidateCredentials(@"user", "password");

                if (isValid == true)
                    return "user is valid";
                else
                    return "user is not valid";
            }

Thursday, July 12, 2012

Related content link doesn't work in InfoPath

Recently I needed to customize task's InfoPath form. Everything went well except that the related link which normally leads you to related item of your task didn't work. After short investigation of this problem I found out that the URL address contains spaces. This was caused by titles of the sites (if site title contains spaces, this spaces are then used in URL).
All you have to do is to create a new field (Hypertext Link) in the SharePoint designer and then in properties of this field set the Default value. Default value is then function like this:
concat(substring-before(Related Content; " "); "%20"; substring-after(Related Content; " "))


Hope this could help somebody :)

How to set URL of the site logo link

Hi everyone :)
I am not much of expert when it comes to SharePoint branding, but recently I needed to solve simple task and because I don't want to forget it I will paste it here :)
Requirements were very simple - SharePoint mastePage has site logo which is usually link to somewhere. You can change this URL in SPDesigner and manually write URL like this "http://www.mySharePointServer.com/", but I wouldn't recommended this approach 'cause if you have at least testing server you would have to change it there to and who wants to remember a lot of stuffs to change after you migrate your master page into different environment :)
So I found this two common variations which you can use to satisfy your requirements (As I wrote before I am not much of expert so there must be more methods to create generated URL and if you know some of them please do not hesitate to comment it. I would be glad to read it).

Link to the root site of the site collection:

<SharePoint:SPLinkButton runat="server" NavigateUrl="~sitecollection/" id="onetidProjectPropertyTitleGraphic">
<SharePoint:SiteLogoImage name="onetidHeadbnnr0" id="onetidHeadbnnr2" LogoImageUrl=" ~sitecollection/ /PublishingImages/Logo.jpg" runat="server"/>
</SharePoint:SPLinkButton>


Link just to the top of the current site:

<SharePoint:SPLinkButton runat="server" NavigateUrl="~site/" id="onetidProjectPropertyTitleGraphic">
<SharePoint:SiteLogoImage name="onetidHeadbnnr0" id="onetidHeadbnnr2" LogoImageUrl=" ~sitecollection/ /PublishingImages/Logo.jpg" runat="server"/>
</SharePoint:SPLinkButton>

Wednesday, July 11, 2012

Windows SharePoint Services Web Services

Sometimes your requirements need to create web services to do something inside SharePoint. Before you start to write your own custom code you can check this site to review if the action you require is not already there http://msdn.microsoft.com/en-us/library/ms479390(v=office.12).aspx

Friday, April 27, 2012

Remove webpart from page

There can be any reason why you wouldn't want to load whole content of the site and you would want to delete some particular webpart from it.
There is simple solution for this - just add this ?Contents=1 on the end of the URL.
Example: http://[yourServerName]/SomeSite/SomeNestedSite/SitePages/Home.aspx?Contents=1

Hope it helps...

Site manager URL

Just in a case that somebody (like me :) ) would forget the URL to the site manager.
http://[yourServerName]/_layouts/sitemanager.aspx

Friday, March 30, 2012

SharePoint visual webpart - Session state can only be used when enableSessionState is set to true, either in a configuration file or in the Page directive. Please also make sure that System.Web.SessionStateModule or a custom session state module is included in the ...

I was creating a new visual webpart for MS SharePoint 2010, but since I needed to use sessions I got this error:
Session state can only be used when enableSessionState is set to true, either in a configuration file or in the Page directive. Please also make sure that System.Web.SessionStateModule or a custom session state module is included in the <configuration>\<system.web>\<httpModules> section in the application configuration.


As error message advice to you, you have to change a config file slightly. Since there is no web.config in visual webpart project, you should change the web.config on your server.
Open the web.config (the one in the folder "intepub") and then set "enableSessionState" property in "pages" tag as below:
<pages enableSessionState="true" ...
then add "remove" and "add" tags to the <system.webServer> (see? Error message advised you to add it to the system.web not to the system.webServer. And this was reason why I was struggling with this for two hours :) )
<system.webServer>
<modules>
<!-- UrlRewriter code here -->
<remove name="Session" />
<add name="Session" type="System.Web.SessionState.SessionStateModule" preCondition="integratedMode" />
</modules>
</system.webServer>

Ok then, thats all... Do not believe alerts everytime ;)

Thursday, March 29, 2012

Manage services on a server

Time to time you may need to manage services on a server. SharePoint can force you to do that by error message like this  :-)  “The timer job for this operation has been created, but it will fail because the administrative service for this server is not enabled. If the timer job is scheduled to run at a later time, you can run the jobs all at once using stsadm.exe -o execadmsvcjobs. To avoid this problem in the future, enable the Windows SharePoint Services administrative service, or run your operation through the STSADM.exe command line utility.“
To start Service window do this:
Start - > Run -> type services.msc -> and find service you need to manage.

In the case of error message above it would be "SharePoint 2010 Administration".

Hope it helps...

Tuesday, February 21, 2012

Unable to see Content Query Webpart in SP 2010

Recently I needed to add Content Query Webpart on the site. I couldn't find this webpart in Webpart Gallery. Short investigation led me to activate appropriate feature. All you have to do is activate the SharePoint Server Publishing Infrastructure feature. Then you should be able to see webpart.
Hope that helps anybody ;)

Thursday, January 26, 2012

How to deploy SharePoint 2010 event receiver (or .wsp package)

This may sounds easy, but it can cause small headache. It happened  to me :) I have developed simple event receiver which creates log to the workflow history list and sends email to somebody. But since I uploaded and activated solution on production server, my solution stopped working. After few minutes of testing and reading log files in 12 hive I found this error message: Request for the permission of type 'System.Net.Mail.SmtpPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
Some articles about deployment
http://msdn.microsoft.com/en-us/library/dd583158(v=office.11).aspx
http://msdn.microsoft.com/en-us/library/ie/gg749858.aspx
http://msdn.microsoft.com/en-us/library/ee231562.aspx
led me to find where real problem was. Assemblies installed to the global assembly cache (GAC) run with Full trust, but when I looked to the GAC I couldn't see my dll. So I tried to install it to the GAC. And since than its working like a charm. Conclusion is that is possible to create wsp file from your project (Visual Studio -> Build -> Package), upload(Share Point (home page) ->  Site Actions -> Site Settings -> Solutions) and activate it. But if your dll is not in GAC you probably won't be able to use some classes as articles from msdn mentioned.
I am not sure if it is best approach but it works for me... So if you know better one, please let me know :)
Happy coding...

Activate solution button is disabled

Recently I solved problem that I couldn't activate my solution. Since you are farm administrator and site collection administrator you are probably able to upload a new solution. And in case that no errors messages are connected with activating solution and activation button is grayed out you can try this approach which helped in my case. My SharePoint farm was installed recently and this was first uploaded solution (this is important part 'cause if you have some solution of yours already uploaded and activated, this solution probably won't be helpful for you)
All you need to do is start Microsoft SharePoint Foundation Sandboxed Code Service service. So go to the Central Administration -> System Settings -> Manage Services on Server and start service I mentioned above.
Hope that helps somebody...