How To Fix The Error 'The relationship 'x' was not loaded because the type 'x' is not available' In Entity Framework



TODO:

You are attempting to query a table, and you receive the message:  The relationship 'x' was not loaded because the type 'x' is not available.

 

SOLUTION:

Ensure your connection string is exists and is valid.  If you renamed your model be sure to change the .csdl and .ssdl entry in the connection string.  Once you correct the connection string, the error will go away.

 

NOTES:

There are no notes on this topic

How To Add A Document As An Attachment To A New SharePoint List Item In C#



TODO:

Have you ever wanted to add a file, as an attachment to a new item in a SharePoint list?

 

SOLUTION:

        /// <summary>Add the contents of a file to a document library</summary>
        /// <param name="DocumentData">byte[] of the document data</param>
        /// <param name="SharePointUrl">The URL to the sharepoint server</param>
        /// <param name="SharePointSite">The name of the site the document library resides</param>
        /// <param name="DocumentLibrary">The name of the document library</param>
        /// <param name="MetaData">Any meta data you want to add.  For instance if there are other columns, you can specify them here.</param>
        /// <param name="OverWriteFile">Overwrite flag.  true or false, self explanatory</param>
        /// <returns></returns>
        public bool AddFileToList(byte[] DocumentData, string SharePointUrl, string SharePointSite, string List, Hashtable MetaData)
        {
            try
            {
                //get the site
                using (SPSite mysiteCollection = new SPSite(SharePointUrl))
                {
                    // Alternately you can use oSite.RootWeb if you want to access the main site
                    // but we will just do a find so we do not need to worry about levels
                    SPWebInfo webinfo = mysiteCollection.AllWebs.WebsInfo.Find(delegate(SPWebInfo w) { return w.Title.ToUpper() == SharePointSite.ToUpper(); });
                    //get the site by title (need to because name could be site/site...)              
                    using (SPWeb rootSite = mysiteCollection.AllWebs[webinfo.Id])   //now get the web by GUID
                    {
                        SPList incompleteList = rootSite.Lists[List];               //the list by display name
                        SPListItem newItem = incompleteList.Items.Add();            //get the item from the file just uploaded

                        //now add each item to the properties
                        if (MetaData != null)
                        {
                            //take each piece of meta data, and apply it to the item
                            foreach (object key in MetaData.Keys)
                            {
                                //newItem.Properties.Add(key, MetaData[key]);
                                newItem[key.ToString()] = MetaData[key];
                            }
                        }

                        newItem.Attachments.Add(string.Format("{0}.xml", Guid.NewGuid()), DocumentData);   //add attachments to the list item
                        newItem.Update();   //update the item
                    }
                }
                return true;
            }
            catch (Exception x)
            {
                return false;
            }
        }

 

NOTES:

The meta data are columns on the item.  You can populate those during the add, by passing them in in a Hashtable.

How To Add Document To A SharePoint Document Library C#



TODO:

Have you ever wanted to add a document to a SharePoint document library?  The below example, is a method that will allow you to do just that.

 

SOLUTION:

        /// <summary>
        /// Add the contents of a file to a document library
        /// </summary>
        /// <param name="DocumentData">byte[] of the document data</param>
        /// <param name="SharePointUrl">The URL to the sharepoint server</param>
        /// <param name="SharePointSite">The name of the site the document library resides</param>
        /// <param name="DocumentLibrary">The name of the document library</param>
        /// <param name="MetaData">Any meta data you want to add.  For instance if there are other columns, you can specify them here.</param>
        /// <param name="OverWriteFile">Overwrite flag.  true or false, self explanatory</param>
        /// <returns></returns>
        public bool AddFileToDocumentLibrary(byte[] DocumentData, string SharePointUrl, string SharePointSite, string DocumentLibrary, Hashtable MetaData, bool OverWriteFile)
        {
            try
            {
                //get the site
                using (SPSite mysiteCollection = new SPSite(SharePointUrl))
                {
                    //get web info by title (i need to do it this way)
                    SPWebInfo webinfo = mysiteCollection.AllWebs.WebsInfo.Find(delegate(SPWebInfo w) { return w.Title.ToUpper() == SharePointSite.ToUpper(); });
                    
                    //get the site by title (need to because name could be site/site...)              
                    using (SPWeb rootSite = mysiteCollection.AllWebs[webinfo.Id])   //now get the web by GUID
                    {
                        SPFile newFile = null;
                        SPFolder incompleteLibrary = rootSite.Folders[DocumentLibrary]; //the list by display name
                        
                        //now create a hash of our fields we want to set, and do it in one shot.
                        if (MetaData == null || MetaData.Count == 0)
                            newFile = incompleteLibrary.Files.Add(string.Format("{0}.xml", Guid.NewGuid()), DocumentData, OverWriteFile);  //add it to the library
                        else
                            newFile = incompleteLibrary.Files.Add(string.Format("{0}.xml", Guid.NewGuid()), DocumentData, MetaData, OverWriteFile);  //add it to the library
                    }
                }
                
                return true;
            }
            catch (Exception x)
            {
                return false;
            }
        }

 

NOTES:

In my case, I was only adding XML files.  Therefore you can change the file name generation to use an extension that is passed in potentially.

How To Remove "Log In" Menu Item From BlogEngine.net Site



TODO:

Have you ever wanted to remove the log in link that is in the menu of sites created with BlogEngine.Net?

 

SOLUTION:

Download the source for BlogEngine.Net.  

Open in Visual Studio

Open BlogEngine.Net\App_Code\Controls\PageMenu.cs

Look for the method "HtmlGenericControl BindPages()"

Comment out "AddMenuItem" in the ELSE of the Security.IsAuthenticated check.

Build the solution, and deploy the new DLL.

Now you will never see "log in", and will see "log off" only if you login by going directly to the log ing page.  ( yoursite.com/Account/Login.aspx )

 

 

private HtmlGenericControl BindPages()
{
            // recursivly get all children of the root page
            HtmlGenericControl ul = GetChildren(Guid.Empty);

            // items that will be appended to the end of menu list
            AddMenuItem(ul, Contact, "~/contact.aspx");

            if (Security.IsAuthenticated)
            {
                AddMenuItem(ul, Logoff, "~/Account/login.aspx?logoff");
            }
            else
            {
                //AddMenuItem(ul, Logon, "~/Account/login.aspx");
            }

            return ul;
}

 

 

NOTES:

There are no notes on this topic

How To Get The nth Day Of A Month



TODO:

Have you ever wanted the 3rd Monay of the month, or some other similar scenario?  Below is a method that will do this for you, as well as some sample calls to it.

int xDayOfMonth = GetNthDayOfMonth(2, System.DayOfWeek.Sunday);  //get the 2nd Sunday of the current month

xDayOfMonth = GetNthDayOfMonth(5, System.DayOfWeek.Tuesday);  //get the LAST tuesday of the current month

xDayOfMonth = GetNthDayOfMonth(3, System.DayOfWeek.Saturday);  //get the third Saturday of the current month

 

SOLUTION:

        public int GetNthDayOfMonth(int nth, DayOfWeek dayOfWeek)
        {
            int day = (int)dayOfWeek;
            DateTime now = DateTime.Now;                                            //get now, in case we span days            
            DateTime firstDayOfMonthDate = new DateTime(now.Year, now.Month, 1);    //now get the first day of month
            DayOfWeek firstDayOfWeek = firstDayOfMonthDate.DayOfWeek;               //now get the day of week
            int firstOfMonthDay = (int)firstDayOfWeek;
            int returnDay = 0;
            int x = (int)System.DayOfWeek.Sunday;
            //now compare day to curr day (sunday==0 fyi)
            if (firstOfMonthDay == day)
            {
                //the first day of the month is what we need, so do the simple math
                returnDay = 1 + (7 * (nth - 1));
            }
            else if (firstOfMonthDay < day) //( ex: wed < thurs )
            {
                //ex.  3rd thurs of Feb 2012 - 1 + (7 *(3-1)) + (4-3) = 16 (16th day of month)
                returnDay = 1 + (7 * (nth - 1)) + (day - firstOfMonthDay);
            }
            else //(firstday > day)  ex: wed > mon )
            {
                //ex.  3rd mon of Feb 2012 - 1 + (7 *(3-1)) + (3+1) = 20 (20th day of month)
                returnDay = 1 + (7 * (nth - 1)) + (firstOfMonthDay + day) + 1; //add one at end to fix 0 offset of DayOfWeek
            }

            //in this case we need to make sure we are not in an invalid date scenario, if so back it out by 7 days
            if (nth == 5)
            {
                DateTime outDate;
                DateTime.TryParse(String.Format("{0}-{1}-{2}", now.Year, now.Month, returnDay), out outDate);

                //if it was bad, minus 7 and go
                if (outDate == DateTime.MinValue || outDate == null)
                    returnDay -= 7;
            }

            return returnDay;
        }

 

NOTES:

There are no notes on this topic.

How To Pass An Parameter To A Thread At Start



TODO:

Have you ever wanted to create a thread, and pass a parameter to it when it starts?

 

SOLUTION:

 

//This code creates the thread, and starts it with a parameter
Thread myThread = new Thread(new ParameterizedThreadStart(MyMethodtoCall));	 //create our job thread
myThread.Start(jobStepsToRun);  //start it now, passing in our parameter


//This method will be use in the ParameterizedThreadStart call
private void MyMethodtoCall(object myPassedParameter)
{
     //here you can access your parameter and use it
}

 

NOTES:

There are no notes on this topic.

How To Encrypt / Protect Web.config Or App.config File



TODO:

Have you ever wanted to protect your web.config file, so that the appsettings and connectionstrings sections could not be read?  Below are 2 methods and a class level variable you can add to your code to protect your app.config or web.config.

 

SOLUTION:

 

private string LastErrorMessage = "";
        
/// <summary>
/// Protect the App.Config
/// </summary>
public void ProtectApplicationConfig()
{
    Configuration standardConfig = null;
    ConnectionStringsSection standardConnectionStringsSection = null;
    AppSettingsSection standardAppSettingsSection = null;

    try
    {
        standardConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

        // Get the connection strings section
        standardConnectionStringsSection = standardConfig.ConnectionStrings;
        standardAppSettingsSection = standardConfig.AppSettings;

        // Protect this section by using the DpapiProtectedConfigurationProvider a.k.a. DataProtectionConfigurationProvider
        if (!standardConnectionStringsSection.SectionInformation.IsProtected)
            standardConnectionStringsSection.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");

        // Protect this section by using the DpapiProtectedConfigurationProvider a.k.a. DataProtectionConfigurationProvider
        if (!standardAppSettingsSection.SectionInformation.IsProtected)
            standardAppSettingsSection.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");

        // Save the configuration section within protected data
        standardConnectionStringsSection.SectionInformation.ForceSave = true;
        standardAppSettingsSection.SectionInformation.ForceSave = true;

        standardConfig.Save();
    }
    catch (Exception x)
    {
        LastErrorMessage = x.Message;
    }
    finally
    {
        standardConfig = null;
        standardConnectionStringsSection = null;
        standardAppSettingsSection = null;
    }
}

/// <summary>
/// Protect the Web.Config
/// </summary>
public void ProtectWebConfig()
{
    Configuration standardConfig = null;
    ConnectionStringsSection standardConnectionStringsSection = null;
    AppSettingsSection standardAppSettingsSection = null;

    try
    {
        standardConfig = WebConfigurationManager.OpenWebConfiguration("~");

        // Get the connection strings section
        standardConnectionStringsSection = (ConnectionStringsSection)standardConfig.GetSection("connectionStrings");
        standardAppSettingsSection = (AppSettingsSection)standardConfig.GetSection("appSettings");

        // Protect this section by using the DpapiProtectedConfigurationProvider a.k.a. DataProtectionConfigurationProvider
        if (!standardConnectionStringsSection.SectionInformation.IsProtected)
            standardConnectionStringsSection.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");

        // Protect this section by using the DpapiProtectedConfigurationProvider a.k.a. DataProtectionConfigurationProvider
        if (!standardAppSettingsSection.SectionInformation.IsProtected)
            standardAppSettingsSection.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");

        // Save the configuration section within protected data
        standardConnectionStringsSection.SectionInformation.ForceSave = true;
        standardAppSettingsSection.SectionInformation.ForceSave = true;

        standardConfig.Save();
    }
    catch (Exception x)
    {
        LastErrorMessage = x.Message;
    }
    finally
    {
        standardConfig = null;
        standardConnectionStringsSection = null;
        standardAppSettingsSection = null;
    }
}

 

 

NOTES:

The config file can ONLY be used on the machine it is protected on.  Once a file is protected, trying to copy the protected file to another machine and use it will not work.

How To Create a Guid Without Dashes Using C#



TODO

Have you ever wanted a Guid and did not want the dashes?

 

SOLUTION:

 

string batchId = Guid.NewGuid().ToString("N");

 

 

NOTES:

There are no notes on this topic.