linqToSQL datetime get latest from table - c#

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;
}

Related

Methods return type in C#

i am using a method to retrieve data from an OPC DA server using TitaniumAS packages, the problem i am having is that i have a lot of tags to read/write so i have to use methods.
The WriteX method works fines as it doesnt have to return anything but the read does not, well it does its job, it reads but i cannot use that data outside of the method because it was a void method, when i tried to use it as a String method (that's the type of data i need) it says :
Error CS0161 'ReadX(string, string)': not all code paths return a value
PS : note that i am just a beginner in C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TitaniumAS.Opc.Client.Common;
using TitaniumAS.Opc.Client.Da;
using TitaniumAS.Opc.Client.Da.Browsing;
using System.Threading;
using System.Threading.Channels;
using Async;
namespace OPCDA
{
class Program
{
static void Main(string[] args)
{
TitaniumAS.Opc.Client.Bootstrap.Initialize();
Uri url = UrlBuilder.Build("Kepware.KEPServerEX.V6");
using (var server = new OpcDaServer(url))
{
server.Connect();
OpcDaGroup group = server.AddGroup("MyGroup");
group.IsActive = true;
Ascon ascon1 = new Ascon();
ReadX("Channel1.Ascon1.AsconS", ascon1.ALM);
Console.WriteLine("value = {0}", ascon1.ALM);
void WriteX(String Link, String Ascon)
{
var definition1 = new OpcDaItemDefinition
{
ItemId = Link,
IsActive = true
};
OpcDaItemDefinition[] definitions = { definition1 };
OpcDaItemResult[] results = group.AddItems(definitions);
OpcDaItem tag = group.Items.FirstOrDefault(i => i.ItemId == Link);
OpcDaItem[] items = { tag };
object[] Values = { Ascon };
HRESULT[] Results = group.Write(items, Values);
}
string ReadX(String Link, String read)
{
var definition1 = new OpcDaItemDefinition
{
ItemId = Link,
IsActive = true
};
OpcDaItemDefinition[] definitions = { definition1 };
OpcDaItemResult[] results = group.AddItems(definitions);
OpcDaItemValue[] values = group.Read(group.Items, OpcDaDataSource.Device);
read = Convert.ToString(values[0].Value);
}
}
}
}
}
the first step was to state the return like this :
return Convert.ToString(values[0].Value) instead of read = Convert.ToString(values[0].Value)
then go up and use that value with my variable :
ascon1.ALM=ReadX("Channel1.Ascon1.AsconS");

Find category's parameter's and combine them in the right order

This code filters elements of certain category and finds and concatenates parameters although what needed is something a little more complex.
First of all, a person needs to be able to choose a category (out of a drop down list) or search and find the necessary ones.
And the second thing is that a user is supposed to specify what parameters he would like to combine (we have shared parameters txt fyi) and choose the order in which they are going to follow one another. Any resource on it or something similar to it would help greatly!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.UI.Selection;
namespace CombineParameters
{
[Transaction(TransactionMode.Manual)]
public class Class : IExternalCommand
{
public Result Execute(ExternalCommandData commandData,
ref string message,
ElementSet elements)
{
UIApplication uiapp = commandData.Application;
UIDocument uidoc = uiapp.ActiveUIDocument;
//Application app = uiapp.Application;
Document doc = uidoc.Document;
//Create Filtered Element Collector and Filter
FilteredElementCollector collector = new FilteredElementCollector(doc);
ElementCategoryFilter filter = new ElementCategoryFilter(BuiltInCategory.OST_DuctFitting);
//Applying Filter
IList <Element> ducts = collector.WherePasses(filter).WhereElementIsNotElementType().ToElements();
foreach (Element e in ducts)
{
//Get Parameter values
string parameterValue1 = e.LookupParameter("AA").AsString();
string parameterValue2 = e.LookupParameter("BB").AsString();
string parameterValue3 = e.LookupParameter("CC").AsString();
string newValue = parameterValue1 + "-" + parameterValue2 + "-" + parameterValue3;
using (Transaction t = new Transaction(doc, "Set Parameter name"))
{
t.Start();
e.LookupParameter("DD").Set(newValue).ToString();
t.Commit();
}
}
return Result.Succeeded;
}
}
}
You want to combine user selected parameters in a specific order? Why dont you use a simple windows form gui.
Example
command.cs
#region Namespaces
using Autodesk.Revit.ApplicationServices;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace combineParameters
{
[Transaction(TransactionMode.Manual)]
public class Command : IExternalCommand
{
public Result Execute(
ExternalCommandData commandData,
ref string message,
ElementSet elements)
{
UIApplication uiapp = commandData.Application;
UIDocument uidoc = uiapp.ActiveUIDocument;
Application app = uiapp.Application;
Document doc = uidoc.Document;
Form1 form = new Form1(doc);
//Show Dialouge form
form.ShowDialog();
return Result.Succeeded;
}
}
}
Forms1.cs
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace combineParameters
{
public partial class Form1 : System.Windows.Forms.Form
{
//Class variable
Document revitDoc { get; set; }
public Form1(Document doc)
{
InitializeComponent();
this.revitDoc = doc;
//Create a list of the parameters you want your user to choose from
List<string> stringParameters = new List<string>
{
"textParameter1",
"textParameter2",
"textParameter3",
"textParameter4"
};
//Add list to comboboxes on form
foreach (string parameterName in stringParameters)
{
comboBox1.Items.Insert(0, parameterName);
comboBox2.Items.Insert(0, parameterName);
comboBox3.Items.Insert(0, parameterName);
}
}
private void button1_Click(object sender, EventArgs e)
{
FilteredElementCollector collector = new FilteredElementCollector(revitDoc);
ElementCategoryFilter filter = new ElementCategoryFilter(BuiltInCategory.OST_DuctFitting);
//Applying Filter
IList<Element> ducts = collector.WherePasses(filter).WhereElementIsNotElementType().ToElements();
using (Transaction t = new Transaction(revitDoc, "Set Parameter name"))
{
//Use a try and catch for transactions
try
{
t.Start();
foreach (Element duct in ducts)
{
//Get Parameter values
string parameterValue1 = duct.LookupParameter(comboBox1.Text).AsString();
string parameterValue2 = duct.LookupParameter(comboBox2.Text).AsString();
string parameterValue3 = duct.LookupParameter(comboBox3.Text).AsString();
string newValue = parameterValue1 + "-" + parameterValue2 + "-" + parameterValue3;
//do not need .ToString() when setting parameter
duct.LookupParameter("NewParameter").Set(newValue);
}
t.Commit();
}
//Catch with error message
catch (Exception err)
{
TaskDialog.Show("Error", err.Message);
t.RollBack();
}
}
}
}
}
Snip of this example inside Revit:
Example photo

opening sap and then proceeding to login screen through c# Automation

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!

import Csv file Oledb C#

Hi please can anyone give me solution to this problem,i have to import csv file using c# but i have this problem in this screenshot
Screen
the separate betwenn column is ',' but in the data there is a rows tha contains ".
Mohamed, I cannot see your screenshot, but can point you toward generic lists and creating a class to represent data. You will need to add references from the "Project" menu.
Microsoft.VisualBasic
System.Configuration
WindowsBase
I am including code from a snippet of code where I was doing that:
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualBasic.FileIO;
namespace CsvToListExp
{
class Program
{
public static void Main(string[] args)
{
// HARD_CODED FOR EXAMPLE ONLY - TO BE RETRIEVED FROM APP.CONFIG IN REAL PROGRAM
string hospPath = #"C:\\events\\inbound\\OBLEN_COB_Active_Inv_Advi_Daily_.csv";
string vendPath = #"C:\\events\\outbound\\Advi_OBlen_Active_Inv_Ack_Daily_.csv";
List<DenialRecord> hospList = new List<DenialRecord>();
List<DenialRecord> vendList = new List<DenialRecord>();
//List<DenialRecord> hospExcpt = new List<DenialRecord>(); // Created at point of use for now
//List<DenialRecord> vendExcpt = new List<DenialRecord>(); // Created at point of use for now
using (TextFieldParser hospParser = new Microsoft.VisualBasic.FileIO.TextFieldParser(hospPath))
{
hospParser.TextFieldType = FieldType.Delimited;
hospParser.SetDelimiters(",");
hospParser.HasFieldsEnclosedInQuotes = false;
hospParser.TrimWhiteSpace = true;
while (!hospParser.EndOfData)
{
try
{
string[] row = hospParser.ReadFields();
if (row.Length <= 7)
{
DenialRecord dr = new DenialRecord(row[0], row[1], row[2], row[3], row[4], row[5], row[6]);
hospList.Add(dr);
}
}
catch (Exception e)
{
// do something
Console.WriteLine("Error is: {0}", e.ToString());
}
}
hospParser.Close();
hospParser.Dispose();
}
using (TextFieldParser vendParser = new Microsoft.VisualBasic.FileIO.TextFieldParser(vendPath))
{
vendParser.TextFieldType = FieldType.Delimited;
vendParser.SetDelimiters(",");
vendParser.HasFieldsEnclosedInQuotes = false;
vendParser.TrimWhiteSpace = true;
while (!vendParser.EndOfData)
{
try
{
string[] row = vendParser.ReadFields();
if (row.Length <= 7)
{
DenialRecord dr = new DenialRecord(row[0], row[1], row[2], row[3], row[4], row[5], row[6]);
vendList.Add(dr);
}
}
catch (Exception e)
{
// do something
Console.WriteLine("Error is: {0}", e.ToString());
}
}
vendParser.Close();
vendParser.Dispose();
}
// Compare the lists each way for denials not in the other source
List<DenialRecord> hospExcpt = hospList.Except(vendList).ToList();
List<DenialRecord> vendExcpt = vendList.Except(hospList).ToList();
}
}
}
Google TestFieldParser and look at the methods, properties and constructors. It is very versatile, but runs slowly due to the layers it goes through. It has the ability to set the delimiter, handle fields wrapped in quotes, trim whitespace and many more.

Automatic number insertion in MySQL with the format "AN-00000000"

My purpose on this is to insert a autonumber for this format AN-00000000 to the db, with the type in db varchar.
my code in windows form is saving a integer number already "10000000".
But I turn on my mind and think if possible that the auto number will be like this AN-00000000 and to save to the db with a character string.
I tried my best to change and apply but suddenly I can not implement because is on the integer part.
I am creating the basic system in our company to create a automate membership for the members, in our company we have 4 parts of membership which is Dep, sep, mep and cef, so I turn on my mind that i need to implement the 4 Id with the following to identify what the department they included. like DEP-00000001, SEP-00000001, MEP-0000001 and CEF-00000001.
Can anyone suggest or give their opinion on my code below? Thanks!
DBconnect.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data;
using MySql.Data.MySqlClient;
using System.Windows.Forms;
using System.Data;
namespace PAIRDevelopment.Classes
{
public class DBConnect
{
public static string csConnect = "uid=root; database=membership; pooling = false; convert zero datetime=True";
public static MySqlConnection csCon= new MySqlConnection(Classes.DBConnect.csConnect);
public MySqlCommand cmdCon = new MySqlCommand();
public MySqlDataReader reader;
public void nonQuery(string cmdText)
{
cmdCon.Connection = csCon;
csCon.Open();
cmdCon.CommandText = cmdText;
cmdCon.ExecuteNonQuery();
cmdCon.Dispose();
csCon.Close();
}
public void OPEN(string cmdtext)
{
cmdCon.Connection = Classes.DBConnect.csCon;
Classes.DBConnect.csCon.Open();
cmdCon.CommandText = cmdtext;
reader = cmdCon.ExecuteReader();
}
public void CLOSE()
{
reader.Close();
cmdCon.Dispose();
Classes.DBConnect.csCon.Close();
}
}
}
Windows Form:
using System;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace PAIRDevelopment
{
public partial class Pair_Individual : Form
{
Classes.DBConnect OpenConCls = new Classes.DBConnect();
public Pair_Individual()
{
InitializeComponent();
textBox6.MaxLength = 13;
}
private void benabled_Click(object sender, EventArgs e)
{
OpenConCls.OPEN("SELECT MAX(piId) FROM tblpair_individual_membership");
while (OpenConCls.reader.Read())
{
string pcount = OpenConCls.reader[0].ToString();
if (pcount.Length == 0)
{
textBox1.Text = "10000000";
}
else
{
//int pcount1 = Convert.ToInt32(pcount);
//int pcountAdd = pcount1 + 1;
int pcount1 = Convert.ToInt32(pcount);
int pcountAdd = pcount1 + 1;
textBox1.Text = pcountAdd.ToString();
}
}
OpenConCls.CLOSE();
}
int pcount1 = Convert.ToInt32(pcount);
You are probably throwing a FormatException on the above line now if the string contains more than 0-9.
FormatException - value does not consist of an optional sign followed by
a sequence of digits (0 through 9).
If you know the first 4 chars will always be "XXX-" (e.g. "MEP-") then why don't you:
int pcount1 = Convert.ToInt32(pcount.Substring(4)); // ######## part
int pcountAdd = pcount1 + 1; // ######## + 1
textBox1.Text = String.Format("{0}-{1:D8}", pcount.Substring(0, 4), pcountAdd);
Which will convert only the numeric part, increment it, and then concatenate it with the first part.
Also you can look into the TryParse method. Which will indicate if your parse succeeded.
TryParse - Converts the string representation of a number to its 32-bit signed
integer equivalent. A return value indicates whether the operation succeeded.

Categories

Resources