I'm using an SSIS script task to try and create a SharePoint subsite. The errors don't tell me anything. I know the problem lies in the ClientContext line. The SQL Server server with SSIS is a separate server from my SharePoint server. Any ideas?
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Client;
using System.Collections.Generic;
using Microsoft.SharePoint.Client.Utilities;
namespace ST_a1ecfb3e46dc4211ac17435ad3bb67ec
{
[Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
{
public void Main()
{
try
{
string SiteDescription = "This is my first site creation using Client Object Model.";
int SiteLanguage = 1033;
string SiteTitle = "Test Site";
string SiteUrl = "Test";
bool SitePermissions = true;
string mywebTemplate = "STS#0";
ClientContext clientContext = new ClientContext("http://extranet.domain.local/");
//Retreive the web from the Client Context. This web is the root web by default.
/*Web oWebsite = clientContext.Web;
//Create a new webCreateInformation object to specify the properties of the new site being created.
WebCreationInformation webCreateInfo = new WebCreationInformation();
webCreateInfo.Description = SiteDescription;
webCreateInfo.Language = SiteLanguage;
webCreateInfo.Title = SiteTitle;
webCreateInfo.Url = SiteUrl;
webCreateInfo.UseSamePermissionsAsParentSite = SitePermissions;
webCreateInfo.WebTemplate = mywebTemplate;
//Adding a new site under the root web
Web oNewWebsite = oWebsite.Webs.Add(webCreateInfo);*/
Dts.TaskResult = (int)ScriptResults.Success;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString(), "Error", MessageBoxButtons.OK);
}
}
enum ScriptResults
{
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};
}
}
Related
I'm trying to delete Microsoft Sharepoint lists items using the SSIS C# script task.
It's working fine on my local computer.
I installed Microsoft.SharePoint. dll on my computer to do this task.
Below is what I have done on an SSIS Package script task.
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using Microsoft.SharePoint.Client;
using System.Linq;
using System.Text;
using System.Net;
using System.Security;
using System.Data.Sql;
using System.Data.OleDb;
using System.Data.SqlClient;
namespace ST_d55693ffa58249c9b326e10762830927
{
[Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
{
public void Main()
{
try
{
string siteUrl = "https://comapany.sharepoint.com/sites/sinfo/IT_TEAM/";
using (ClientContext clientContext = new ClientContext(siteUrl))
{
var passWord = new SecureString();
foreach (char c in "******************".ToCharArray()) passWord.AppendChar(c);
clientContext.Credentials = new SharePointOnlineCredentials("user#comapany.com", passWord);
Web oWebsite = clientContext.Web;
List oList = oWebsite.Lists.GetByTitle("TEST_S");
ListItemCollectionPosition licp = null;
clientContext.Load(oList);
clientContext.ExecuteQuery();
int itemCount = oList.ItemCount;
while (true)
{
CamlQuery query = new CamlQuery();
query.ViewXml
= #"<View><ViewFields><FieldRef Name='ID'/></ViewFields><RowLimit>250</RowLimit></View>";
query.ListItemCollectionPosition = licp;
ListItemCollection items = oList.GetItems(query);
clientContext.Load(items);
clientContext.ExecuteQuery();
licp = items.ListItemCollectionPosition;
itemCount -= items.Count;
foreach (ListItem itm in items.ToList())
{
itm.DeleteObject();
}
clientContext.ExecuteQuery();
if (licp == null)
{
break;
}
}
}
}
catch (Exception e)
{
SqlConnection con = new SqlConnection("Data Source=PROD_20;Initial Catalog=TEAM_DATA;Integrated Security=SSPI;");
con.Open();
string qry = "INSERT INTO ASSIST.ERROR_LOGS(PACKAGE,METHOD,MESSAGE,TIME_OCCURED) VALUES(#Package,#Method,#Message,#Time);";
SqlCommand cmd = new SqlCommand(qry, con);
cmd.Parameters.Add("#Package", SqlDbType.VarChar, 20);
cmd.Parameters.Add("#Method", SqlDbType.VarChar, 30);
cmd.Parameters.Add("#Message", SqlDbType.NVarChar, 255);
cmd.Parameters.Add("#Time", SqlDbType.DateTime);
cmd.Parameters["#Package"].Value = "PRE_SP";
cmd.Parameters["#Method"].Value = "PRE MAIN";
cmd.Parameters["#Message"].Value = e.Message.ToString();
cmd.Parameters["#Time"].Value = DateTime.Now;
cmd.ExecuteNonQuery();
con.Close();
}
Dts.TaskResult = (int)ScriptResults.Success;
}
enum ScriptResults
{
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};
}
}
After deploying the package on to the Production server.
It is throwing an exception like Exception has been thrown by the target of an invocation.
is this something to do with the Prod service account to have access on the Sharepoint Site.
I am trying to open sap and connect to the gui using the following code . I Had to remove the earlier post due to some mistakes in post . I want to open sap logon 730 screen and then proceed to logon screen where i want to login using some credentials.I am getting some errors of connection entry point not found in the first code named opensap . login is working now. BUt still i cant make the SapBOX screen automatically process to the login screen. Please help in the code . Any help will be highly appreciated . Thanks
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SAPFEWSELib;
using SapROTWr;
using AVTAR.SAPLibrary;
using AVTAR.CustomLibrary;
namespace AvatarTest1 {
public class Sap {
public static GuiApplication SapGuiApp { get; set; }
public static GuiConnection SapConnection { get; set; }
public static GuiSession SapSession { get; set; }
public static void openSap(string env) {
Sap.SapGuiApp = new GuiApplication();
string connectString = null;
if (env.ToUpper().Equals("DEFAULT")) {
connectString = "1.0 Test ERP (DEFAULT)";
//connectString = "ASHOST = n7p.naan.as.com SYSNR = N7P
CLIENT =
460 _USER = ***** PASSWD = ****";*******";
} else {
connectString = env;
}
Sap.SapConnection = Sap.SapGuiApp.OpenConnection(connectString,
Sync: true); //creates connection
//Sap.SapSession = (GuiSession)Sap.SapConnection.Sessions.Item(0);
//creates the Gui session off the connection you made
}
public void Login(string userId,string pass,string clientid) {
try {
for (int i = 0; i <= 50; i++) {
Sap.SapSession = SapGuiApp.ActiveSession;
}
// System.Diagnostics.Process.Start(#"C:\Program
Files\SAP\FrontEnd\SAPgui\saplogon.exe");
GuiTextField Clientfield =
(GuiTextField)SapSession.ActiveWindow.FindById("wnd[0] / usr / txtRSYST -
MANDT");
GuiTextField UserIDField =
(GuiTextField)SapSession.ActiveWindow.FindById("wnd[0]/usr/txtRSYST-BNAME");
GuiTextField PassField =
(GuiTextField)SapSession.ActiveWindow.FindById("wnd[0]/usr/pwdRSYST-BCODE");
//GuiTextField LanguageField =
(GuiTextField)SapSession.ActiveWindow.FindById("wnd[0]/usr/txtRSYST-BNAME");
Clientfield.SetFocus();
Clientfield.Text = clientid;
UserIDField.SetFocus();
UserIDField.Text = userId;
PassField.SetFocus();
PassField.Text = pass;
//Sap.SapSession ssn= new SapSession.FindById("wnd[0]")
GuiButton enter =
(GuiButton)SapSession.ActiveWindow.FindById("wnd[0]");
enter.Press();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
In your Code you commented out "System.Diagnostics.Process.Start(#"C:\Program
Files\SAP\FrontEnd\SAPgui\saplogon.exe");"
Go with this aproach, but use "sapshcut.exe" from the same Folder instead!
(this will be available on the most systems)
In this case it could be as simple as that:
string strProg="C:\Program Files\SAP\FrontEnd\SAPgui\sapshcut.exe";
string strParam="-system=N7P -client=460 -user=youruser -password=yourpassword -language=EN";
System.Diagnostics.Process.Start(strProg,strParam);
Find an (VBA)Examle with some pre-Tests on the Commanline at trouble using excel macro for access to sap
Hope this will do ist for you!
If it is possible to integrate Google big query with C# console application?.
If yes how we can do, i searched over internet i could not find proper answer for that.
I want connection string format? I have created Client ID from Google Developer console how authentication has done? It is one time configuration or every time we need to login in google account to authenticate.
If there is any sample application to connect sample data it would be helpful.
Thanks,
Selvakumar S
Here's a working sample based on another question in StackOverflow:
using DotNetOpenAuth.OAuth2;
using Google.Apis.Authentication.OAuth2;
using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;
using Google.Apis.Bigquery.v2;
using Google.Apis.Bigquery.v2.Data;
using Google.Apis.Util;
using System;
using System.Diagnostics;
using System.Collections.Generic;
namespace BigQueryConsole
{
public class BigQueryConsole
{
// Put your client ID and secret here (from https://developers.google.com/console)
// Use the installed app flow here.
// Client ID looks like "9999999.apps.googleusercontent.com"
static string clientId = "YOURCLIENTID";
static string clientSecret = "YOURSECRET";
// Project ID is in the URL of your project on the APIs Console
// Project ID looks like "999999";
static string projectId = "YOURPROJECTID";
// Query in SQL-like form
static string query = "SELECT state, count(*) from [publicdata:samples.natality] GROUP BY state ORDER BY state ASC";
public static void Main(string[] args)
{
// Register an authenticator.
var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description);
provider.ClientIdentifier = clientId;
provider.ClientSecret = clientSecret;
// Initiate an OAuth 2.0 flow to get an access token
var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization);
// Create the service.
var service = new BigqueryService(auth);
JobsResource j = service.Jobs;
QueryRequest qr = new QueryRequest();
qr.Query = query;
QueryResponse response = j.Query(qr, projectId).Fetch();
foreach (TableRow row in response.Rows)
{
List<string> list = new List<string>();
foreach (TableRow.FData field in row.F)
{
list.Add(field.V);
}
Console.WriteLine(String.Join("\t", list));
}
Console.WriteLine("\nPress enter to exit");
Console.ReadLine();
}
private static IAuthorizationState GetAuthorization(NativeApplicationClient arg)
{
// Get the auth URL:
IAuthorizationState state = new AuthorizationState(new[] { BigqueryService.Scopes.Bigquery.GetStringValue() });
state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
Uri authUri = arg.RequestUserAuthorization(state);
// Request authorization from the user (by opening a browser window):
Process.Start(authUri.ToString());
Console.Write(" Authorization Code: ");
string authCode = Console.ReadLine();
Console.WriteLine();
// Retrieve the access token by using the authorization code:
return arg.ProcessUserAuthorization(authCode, state);
}
}
}
In your answer i could not able to add namespace
"using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;"
But i manage to retrieve results from BigQuery using below code, you need to update Project Name, Project Id and Query.
Download Client ID (I am using Installed Application - Other category ) generate JSON file and add into your Debug folder.
using Google.Apis.Auth.OAuth2;
using System.IO;
using System.Threading;
using Google.Apis.Bigquery.v2;
using Google.Apis.Bigquery.v2.Data;
using System.Data;
using Google.Apis.Services;
using System;
namespace GoogleBigQuery
{
public class Class1
{
private static void Main()
{
UserCredential credential;
using (var stream = new FileStream("client_secrets.json", FileMode.Open,
FileAccess.Read))
{
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
new[] { BigqueryService.Scope.Bigquery },
"user", CancellationToken.None).Result;
}
// Create and initialize the Bigquery service. Use the Project Name value
// from the New Project window for the ApplicationName variable.
BigqueryService Service = new BigqueryService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "PROJECT NAME"
});
string query = "YOUR QUERY";
JobsResource j = Service.Jobs;
QueryRequest qr = new QueryRequest();
qr.Query = query;
DataTable DT = new DataTable();
int i = 0;
QueryResponse response = j.Query(qr, "PROJECT ID").Execute();
if (response != null)
{
int colCount = response.Schema.Fields.Count;
foreach (var Column in response.Schema.Fields)
{
DT.Columns.Add(Column.Name);
}
foreach (TableRow row in response.Rows)
{
DataRow dr = DT.NewRow();
for (i = 0; i < colCount; i++)
{
dr[i] = row.F[i].V;
}
DT.Rows.Add(dr);
}
}
else
{
Console.WriteLine("Response is null");
}
}
}
}
Thanks.
I am writing a Windows Phone 8.1 App (WINRT).
How to do GooglePlus Authentication (SignIn via GooglePlus) in Windows Phone 8.1 App** without using MVVM/MVC**?
I used Web Authentication via Webbrowser control in Windows Phone 8.0 App but Windows Phone 8.1 WebView Control does not have Navigating event.
Can anyone help me?
According to Mr. Filip Skakun, I wrote:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.ApplicationModel.Activation;
using Windows.Data.Json;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Security.Authentication.Web;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.Web.Http;
namespace webbrokerFinal
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
Connect();
this.NavigationCacheMode = NavigationCacheMode.Required;
}
string FacebookClientIDString = "000000000000";
string FacebookCallbackUrlString = " https://www.facebook.com/connect/login_success.html";
private void Connect()
{
try
{
String FacebookURL = "https://www.facebook.com/dialog/oauth?client_id=" + FacebookClientIDString + "&redirect_uri=" + Uri.EscapeUriString(FacebookCallbackUrlString) + "&scope=read_stream&display=popup&response_type=token";
System.Uri StartUri = new Uri(FacebookURL);
System.Uri EndUri = new Uri(FacebookCallbackUrlString);
WebAuthenticationBroker.AuthenticateAndContinue(StartUri, EndUri, null, WebAuthenticationOptions.None);
}
catch (Exception Error) >> The remote procedure call failed. (Exception from HRESULT: 0x800706BE)
{
//
// Bad Parameter, SSL/TLS Errors and Network Unavailable errors are to be handled here.
//
}
}
public async void ContinueWebAuthentication(WebAuthenticationBrokerContinuationEventArgs args)
{
WebAuthenticationResult result = args.WebAuthenticationResult;
if (result.ResponseStatus == WebAuthenticationStatus.Success)
{
await GetFacebookUserNameAsync(result.ResponseData.ToString());
}
else if (result.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
{
}
else
{
}
}
private async Task GetFacebookUserNameAsync(string webAuthResultResponseData)
{
//Get Access Token first
string responseData = webAuthResultResponseData.Substring(webAuthResultResponseData.IndexOf("access_token"));
String[] keyValPairs = responseData.Split('&');
string access_token = null;
string expires_in = null;
for (int i = 0; i < keyValPairs.Length; i++)
{
String[] splits = keyValPairs[i].Split('=');
switch (splits[0])
{
case "access_token":
access_token = splits[1]; //you may want to store access_token for further use. Look at Scenario5 (Account Management).
break;
case "expires_in":
expires_in = splits[1];
break;
}
}
//Request User info.
HttpClient httpClient = new HttpClient();
string response = await httpClient.GetStringAsync(new Uri("https://graph.facebook.com/me?access_token=" + access_token));
JsonObject value = JsonValue.Parse(response).GetObject();
string facebookUserName = value.GetNamedString("name");
}
}
}
But giving me error:
The remote procedure call failed. (Exception from HRESULT: 0x800706BE)
I'd start with WebAuthenticationBroker. It's a sort of wrapper around WebView you use for all OAuth.
Hi I trying to get the max timedate from a table using LinqToSQL. I already asked a similar question, but was trying to do something a bit more specific, and no one was able to help. This time, i would not mind using any solution, short of an Execute SQL task in another part of the SSIS package. This is my whole code. I was trying just to get the Identity column and it wasnt even working, so ignore the ToString please if it seems out of place. I just want to get the latest CREATED_TIMESTAMP please
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using System.IO;
using System.Linq;
using System.Data.SqlClient;
using System.Linq.Expressions;
using System.Collections;
using System.Collections.Generic;
using System.Data.Linq.Mapping;
using System.Data.Linq;
namespace ST_663004ffff194a14b84e2291578ada33.csproj
{
[System.AddIn.AddIn("ScriptMain", Version = "1.0", Publisher = "", Description = "")]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
{
#region VSTA generated code
enum ScriptResults
{
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};
#endregion
//Strings for connections
string iFileName;
string oFileName;
string RW;
public void Main()
{
Dts.Variables["latestTableRow"].Value = getLatest();
MessageBox.Show(getLatest());
Dts.TaskResult = (int)ScriptResults.Success;
}// End Main
public string getLatest()
{
string result = "";
////temp dummy/defaul date is two days ago
//DateTime result = new DateTime();
//result = DateTime.Now.AddDays(-2);
try
{
//get the data connection string from the connection manager
RW = (string)Dts.Connections["ReportingWarehouse"].ConnectionString;
//Remove the Provider, Auto Translate, and Application
//as it is not a parameter for the DataContext constructor
RW = RW.Remove(RW.IndexOf("Provider=SQLNCLI10.1;"), "Provider=SQLNCLI10.1;".Length);
RW = RW.Remove(RW.IndexOf("Auto Translate=False;"), "Provider=SQLNCLI10.1;".Length);
RW = RW.Remove(RW.IndexOf("Application"),RW.Length - RW.IndexOf("Application"));
MessageBox.Show(RW);
//get the last insertion date from the SSASLoging table
using (DataContext RWData = new DataContext(RW))
{
Table<SSASLogging> records = RWData.GetTable<SSASLogging>();
var rs = (from r in records
orderby r.TimeStamp descending
select r).Max();
result = rs.Errorval.ToString();
}
MessageBox.Show(result);
}
catch (Exception e)
{
MessageBox.Show("Exception in retreiving latest time: " + e.Message + "/n"
+ e.StackTrace);
}
return result;
}
}//end partial class
[Table(Name = "SSASLogging")]
public class SSASLogging
{
private DateTime timeStamp;
[Column(Name = "CREATED_TIMESTAMP")]
public DateTime TimeStamp
{
get { return this.timeStamp; }
private set { ;}
}
}//End SSASLogging
}
Ok this works
using (DataContext RWData = new DataContext(RW))
{
Table<SSASLogging> records = RWData.GetTable<SSASLogging>();
var rs = (from r in records
select r).Max(r => r.TimeStamp);
result = rs;
}