Showing posts with label .NET. Show all posts
Showing posts with label .NET. Show all posts

Tuesday, February 2, 2016

SP2010 C# CSOM: Update Created and Modified dates and author

Tested on SharePoint 2010 only. I wanted to have something that could run on a client machine that could help update metadata for a folder or file in a list / document library.

This is a console application written in C#. Obviously, to do something in SharePoint 2010 automation, you will need to download the SP2010 foundation and install some runtime components.

(Or if you are feeling lazy, just copy Microsoft.SharePoint.Client.dll and Microsoft.SharePoint.Client.Runtime.dll and reference them in your project).

To make this piece of code work, you need to know the ID of your list/folder item. There are other methods of retrieving based on URL.

Sunday, February 1, 2015

AgilePoint InfoPath C# snippet - Retrieve repeating row data

Sometimes we would need to manipulate data from an InfoPath repeating field, use this data in our AgilePoint workflows. We would need to add custom code for this by using the Advanced Extensions - Managed Code stencil.

Sample of InfoPath schema:



I have a repeating row called Item with 3 fields or nodes.

My example would be to invoke a subprocess for each row of that data.
In order to access the data, I would need the System.Xml and System.Xml.XPath references in my code. I will make use of the XPathNavigator and XPathIterator functions to get data.

Sunday, November 2, 2014

Convert PowerPoint slides to Images in C#

One of the challenges I have come across is to have a component that could batch convert PPT and PPTX files into images.

I know there are really good components out there like Aspose, but IT budget is always a constraint.
As we already had Office 2010 installed on our machine, I came up with a quick console application t perform the function.

Obviously, you need Office 2010 installed on the machine where you need to run the tool. I compiled the project for the .NET 2.0 Framework.

Just add some references to your Visual Studio 2010 solution like below:
Microsoft.Office.Interop.PowerPoint (from .NET, v14.0.0.0)
Microsoft.Office.Core (from COM, v14.0.0.0)
Others like System.Configuration (as I am using app.config)

After creating a basic C# Console application, add the references mentioned above.

Thursday, June 5, 2014

Get the DLLs from the Global Assembly Cache (GAC)

You might have some software installed on your server, and registers the assemblies to the Global Assembly Cache. Typically, installers would register the assemblies but remove any accessible copy from the local disk as everything is packaged inside the msi or setup file.

There is a really simple way to extract the dlls from GAC, though.
Launch MS DOS, and change directory to c:windows\assembly\gac_msil (you won't be able to open this in windows explorer)!
run the xcopy command. Example:

Note: there are alternative ways such as modifying the registry, or temporarily uninstalling certain dlls to allow browsing from windows explorer, but I would seriously advise against that.

Monday, May 5, 2014

SharePoint InfoPath 2010: C# populate rows in a repeating table

I had an InfoPath form where I needed to have 2 views. In the 2nd view, some information in the repeating table would be automatically populated based on the information entered in the first view.

Initially I wanted to use a rule-only approach but it ended up being too cumbersome; I had to resort to code :(

I will use a time card with date range as an example here. The repeating table will have one row for each day within the date range I have selected.

Friday, March 14, 2014

AgilePoint Infopath integration: XML content as parameter

If you ever need to pass the entire XML document/body of an InfoPath as a parameter in AgilePoint, use this:
$//
Just like any other attributes that you reference ($AttrName)

For example, when you are making use of a web service that accepts an XML document as a parameter.

When you are using managed C# code, you can do this instead:

Sunday, March 2, 2014

C# Update InfoPath by passing in the XPath

C# code snippet to update the InfoPath XML file in a SharePoint library.

Sample parameters:
websiteUrl: http://sharepoint
library Name: InfoPath Library
list Id: 1
xpath: /my:myFields/my:Employees/my:Employee[my:ID='123']/my:Location
value: San Jose

What it does:
In the repeating group Employees, locate the employee whose ID is 123, and update the location to San Jose.

Wednesday, February 26, 2014

AgilePoint C# API: Updating a custom attribute

There are a couple of ways you could employ to update a custom process attribute in AgilePoint. If you have the premier license, it's available as a stencil under Premier Extension. This is pretty handy when you have simple, straightforward values.

However, when you need to manipulate data or perform complex data calculations prior to the update, you can make use of the Managed C# code stencil instead. It can be found under Advanced Extensions.
With just a simple line, you're on your way:
api.SetCustomAttr(pi.WorkObjectID, "YourAttributeName", "TheValue");

Retrieving?
string x = (string)api.GetCustomAttr(pi.WorkObjectID, "YourAttributeName");      

Thursday, June 2, 2011

C# Accessing a MasterPage's variables

Place this block of code in Page_Load()

((myMaster)this.Master).strPageTitle = "Some String";

myMaster being the name of the MasterPage class.

Sunday, May 29, 2011

C# Read Excel file (.xls) using JET OLEDB Provider

public static void extractExcelContent()
{
string path = "D:\shared\file.xls";
if (File.Exists(path))
{
//create the "database" connection string (FOR EXCEL)
string connString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=\"" + path + "\";" +
"Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1;\"";
//create the database query
string query = "SELECT * FROM [FirstExcelSheet$]";

//create a DataTable to hold the query results
DataTable dTable = new DataTable();

//create an OleDbDataAdapter to execute the query
using (OleDbDataAdapter dAdapter = new OleDbDataAdapter(query, connString))
{
try
{
//fill the DataTable
dAdapter.Fill(dTable);
if (dTable.Rows.Count > 0)
{
foreach (DataRow row in dTable.Rows)
{
string fiscalDate = row["FiscalDate"].ToString();
string currency = row["Currency"].ToString();
double rate;
double.TryParse(row["Rate"].ToString(), out rate);
try
{
//do something
}
catch (Exception ex)
{
Console.Writeline("Error while updateExchangeRate: " + ex.ToString());
}

}
}
}
catch (InvalidOperationException e)
{
Console.Writeline(e.ToString());
}
dAdapter.Dispose();
}

//Optional: rename file
DateTime dtNow = DateTime.Now.AddDays(-1);
File.Move(path, path + dtNow.ToString("yyyy-MM-dd"));
}

}

Very quick way to generate Excel file from C#. LOVE IT!

Download the DLL from Google Code and include it in the C# project.
http://code.google.com/p/excellibrary/

//Create the dataset
DataSet ds = new DataSet();

//Set the locale for each
ds.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;

//Create connection
SqlConnection sConn = new SqlConnection();
sConn.ConnectionString = ConnectionString;
sConn.Open();

// Execute stored procedure and fill dataset
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "sp_sample_stored_procedure";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = sConn;

SqlParameter param = new SqlParameter("Name", SqlDbType.NVarChar);
param.Direction = ParameterDirection.Input;
param.Value = name;
cmd.Parameters.Add(param);

SqlDataAdapter sAdapter = new SqlDataAdapter(cmd);
sAdapter.Fill(ds);
sConn.Close();

//Populate Excel worksheet from the data set
ExcelLibrary.DataSetHelper.CreateWorkbook("file.xls", ds);

Login to a website and download file using C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Configuration;
using System.IO;

namespace HttpBrowsing
{
class SimulateHttp
{
private HttpWebRequest request;
private CookieContainer cookieContainer = new CookieContainer();

public bool doLogin(string uid, string pwd, string url)
{
// Create a request using a URL that can receive a post.
request = (HttpWebRequest)HttpWebRequest.Create(url);
request.CookieContainer = cookieContainer;

// Set the Method property of the request to POST.
request.Method = "POST";

// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";

// Create POST data and convert it to a byte array.
string postData = "user_name=" + uid + "&user_password=" + pwd;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);

// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
request.KeepAlive = true;

// Get the request stream.
using (Stream dataStream = request.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}

HttpWebResponse response = (HttpWebResponse)request.GetResponse();
response.Cookies = request.CookieContainer.GetCookies(request.RequestUri);
response.Close();
return true;

}

public void downloadFile(string url, string fileName)
{
// Create a request using a URL that can receive a post.
request = (HttpWebRequest)HttpWebRequest.Create(url);
request.CookieContainer = cookieContainer;

// Set the Method property of the request to GET.
request.Method = "GET";

// Get the response.
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(responseStream))
{
using (StreamWriter writer = new StreamWriter(fileName, false))
{
writer.Write(reader.ReadToEnd());
writer.Flush();
writer.Close();
}
}
responseStream.Close();
}
response.Close();
}
}

public void doLogout(string url)
{
// Create a request using a URL that can receive a post.
request = (HttpWebRequest)HttpWebRequest.Create(url);
request.CookieContainer = cookieContainer;

// Set the Method property of the request to POST.
request.Method = "GET";

HttpWebResponse response = (HttpWebResponse)request.GetResponse();
response.Close();
}

}
Related Posts Plugin for WordPress, Blogger...