How To Call Stored Procedure In C# That Has Output Parameters



TODO:

Have you ever wanted to call a stored procedure in C# that has output parameters?

 

SOLUTIONS:

System.Data.Objects.ObjectParameter param1 = new ObjectParameter("paraminsp1", typeof(bool));
System.Data.Objects.ObjectParameter param2 = new ObjectParameter("paraminsp2", 0.000);           //default so EF works

using (MyEntities MyDatabase = new MyEntities())
{
     MyDatabase.sp_name(x, 2, param1, param2);
}

 

NOTES:

There are no notes on this topic

Where Did Detach() Go In Entity Framework



TODO:

You are migrating old code to the latest version of Entity Framework, and you no longer have the Detach() method.  To fix, use the code below.

 

SOLUTION:

((IObjectContextAdapter)myModel).ObjectContext.Detach(myobject);

 

NOTES:

There are no notes on this topic.

How To Pass A DataTable To A Stored Procedure Using C# and SQL Server



TODO:

Have you ever wanted to pass a DataTable from your C# application to a Stored Procedure in SQL Server?

 

SOLUTION:

Step 1:  Create the User-Definied Table Type in SQL Server

CREATE TYPE [dbo].[MyUserDefinedType] AS TABLE(
	[Id] [int] NULL,
	[FieldOne] [int] NULL,
	[FieldTwo] [int] NULL
)

 

Step 2:  Create the DataTable and call the Stored Procedure

using (DataTable myDataTable = new DataTable())
{
     myDataTable.Columns.Add(“FieldOne”, System.Type.GetType("System.Int32"));
     myDataTable.Columns.Add(“FieldTwo, System.Type.GetType("System.Int32"));
     myDataTable.Columns.Add(“FieldThree, System.Type.GetType("System.Int32"));
                
     DataRow dataRow = null;
                
     for (int i = 0; i < 100; i++)
     {
          dataRow = myDataTable.NewRow();  
          dataRow[“FieldOne] = 1;
          dataRow[“FieldTwo”] = 2;
          dataRow[“FieldThree] = 3;
          myDataTable.Rows.Add(dataRow);           
     }

     using (SqlConnection connection = new SqlConnection(“connectionstring”))
     {
          
          using (SqlCommand command = connection.CreateCommand())
          {
               connection.Open();
               command.CommandType = CommandType.StoredProcedure;
               command.CommandTimeout = 90;
               command.CommandText = “MyStoredProcedureName;
               command.Parameters.AddWithValue(“@IncomingDataTable”, myDataTable);
               command.ExecuteNonQuery();
          }
     }
}


Step 3:  Create the Table

CREATE TABLE MyTable(FieldOne int NULL, FieldTwo NULL, FieldThree NULL)

 

Step 4:  Create the Stored Procedure

CREATE PROCEDURE [dbo].[MyStoredProcedure]
@MyUserDefinedType MyUserDefinedType READONLY

AS
BEGIN 

    INSERT INTO dbo.MyTable
	([FieldOne], [FieldTwo], [FieldThree])
	
	SELECT [FieldOne], [FieldTwo], [FieldThree] FROM @MyUserDefinedType

END

 

 

NOTES:

Be sure that the DataTable columns are added in the SAME order as they are created in the SQL Server User Type.

How To Configure Log4Net In A C# Application



TODO:

Have you ever wanted to use log4net in your C# application?

 

SOLUTION:

To do so, you need to do 2 things:

 

Step 1:  Add the following entry to the bottom of your AssemblyInfo.cs file

[assembly: log4net.Config.XmlConfigurator(Watch = true)]

 

Step 2:  Add this entry to your web or app.config file

<configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
  </configSections>
 
  <log4net>
    <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="c:\YOUR DIRECTORY HERE\your log file name.log" />
      <appendToFile value="true" />
      <rollingStyle value="Composite" />
      <datePattern value="yyyyMMdd" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="30MB" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%d %-5level %logger{1} : %message%newline" />
      </layout>
    </appender>
    <root>
      <level value="ALL" />
      <appender-ref ref="RollingFileAppender" />
    </root>
  </log4net>

 

NOTES:

If you already have a "configSections" entry, just add the new key to that section

How To Fix Web Service Negotiate Login Errors Using C#



TODO:

Have you ever had an issue calling a web service due to the fact that you need to provide credentials to the service?  The below example calls a web service that has an API level user / pass, and also a network user / pass.

 

SOLUTION:

ServiceApi.API api = new ServiceApi.API();

//API Credentials
ServiceCredentials credentials = new ServiceCredentials();
credentials.Username = "user";
credentials.Password = "password";

//Creds, for 401. challenge
System.Net.CredentialCache cc = new System.Net.CredentialCache();
System.Net.NetworkCredential creds = new System.Net.NetworkCredential("user", "pass", "domain");
cc.Add(new Uri("https://webservice.url"), "Negotiate", creds);
api.Credentials = creds;
            
string result = api.GetResultscredentials);

 

NOTES:

Replace the first user / pass with your web service password.  Replace the second set of user / password with your network user / password.

How To Round A Decimal Down To The Nearest Whole Number Using C#



TODO:

Have you ever wanted to round a number down to the nearest whole number using C#.  Example:  14.789 rounded down to 14

 

SOLUTION:

Math.Truncate(14.789)  //produces 14

 

NOTES:

There are no notes on this topic.

How To Download A File From A Document Library Using The SharePoint Client Object Model



TODO:

Have you ever wanted to download a document from a document library using the SharePoint client object model?

 

SOLUTION:

using SP = Microsoft.SharePoint.Client;

//class and code go here

string saveLocation = "C:\\Temp\\";

//SET YOUR ITEM HERE!!!!!!
SP.ListItem item = null;

using (SP.FileInformation fileInformation = SP.File.OpenBinaryDirect(put your context here, (string)item["FileRef"]))
{
     string fileName = (string)item["FileRef"];
     fileName = string.Concat(saveLocation, fileName.Substring(fileName.LastIndexOf("/")+1)); //get the name of the file based on last '/'

     //now save it
     using (System.IO.FileStream outPutFile = System.IO.File.OpenWrite(fileName))
     {
          fileInformation.Stream.CopyTo(outPutFile);
          fileInformation.Stream.Close();
     }
}

 

NOTES:

There are no notes on this topic

How To Zip A Directory Using C#



TODO:

Have you ever wanted to zip an entire directory using C#?

 

SOLUTION:

using System.IO.Compression;

//class and other code here...

//zip the entire directory
//parameter 1 is the directory to zip
//parameter 2 is the resulting zip file
ZipFile.CreateFromDirectory(directoryToZip, zipFilePath);

 

NOTES:

There are no notes on this topic

How To Open Explorer To A Specific Directory Using C#



TODO:

Have you ever wanted to launch explorer from your C# application to a specified directory?

 

SOLUTION:

using System.Diagnostics;

//class and other code goes here...

//set your location here
string explorerLocation = "C:\\Temp\\MyLocation";

//open the location
System.Diagnostics.Process.Start(explorerLocation);

 

NOTES:

There are no notes on this topic

How To Get The Text Value Rather Than The HTML Value Of A MultiLine ListItem Using SharePoint Client Object Model



TODO:

You have a multi-line field in a list.  When you get the value, it comes back as HTML when you reference it as item["field"].  To get the text, rather than the HTML, you need to do the following.

 

SOLUTION:

//put at top!!!
using SP = Microsoft.SharePoint.Client;
 
//put inside class !!! 
SP.ListItem targetItem = null;
//todo, set your targetItem = to the item you want.
 
using(ClientContext clientContext = new ClientContext("http://your.url.goes.here"))
{
     var itemFieldValues = targetItem.FieldValuesAsText;
     clientContext.Load(itemFieldValues);
     clientContext.ExecuteQuery();
}
string fieldTextValue = itemFieldValues["My item Title"];

 

NOTES:

There are no notes on this topic.