c# generating INSERT script with data from database - c#

I try to generate a script which is contains datas in INSERT script forms,
I try to use a reference (see below) to do it
using Microsoft.SqlServer.Management.Smo;
with this code draft
Server serv = new Server(db);
Database simba = serv.Databases[dbname];
string script = "";
ScriptingOptions so = new ScriptingOptions()
{
ScriptData = true,
ScriptSchema = false,
ScriptDrops = false
};
foreach (Table tb in simba.Tables)
{
if (tables.Contains(tb.Name))
{
var sc = tb.Script(so);
foreach (var s in sc)
script += s;
}
using (StreamWriter writer = new StreamWriter(file))
{
foreach (string tab in tables)
writer.WriteLine(script);
}
}
but this code get an error on
var sc = tb.Script(so);
which is
Microsoft.SqlServer.Management.Smo.FailedOperationException
thanks for all reply

I have this code and it is working fine try to use it
var report = string.Empty;
var fileName = Server.MapPath(Constants.BACKUP_FILE_NAME);
var server = new Server(new ServerConnection(new SqlConnection(Constants.BACKUP_CONNECTION_STRING)));
var options = new ScriptingOptions();
var databases = server.Databases[Constants.BACKUP_DATABASE_NAME];
options.FileName = fileName;
options.EnforceScriptingOptions = true;
options.WithDependencies = true;
options.IncludeHeaders = true;
options.ScriptDrops = false;
options.AppendToFile = true;
options.ScriptSchema = true;
options.ScriptData = true;
options.Indexes = true;
report = "<h4>Table Scripts</h4>";
foreach (var table in Constants.BACKUP_TABLES)
{
databases.Tables[table, Constants.BACKUP_SCHEMA_NAME].EnumScript(options);
report += "Script Generated: " + table + "<br>";
}
The "Constants" is my class to hold the constant values like file name, db etc and I am generating script for limited tables so for that reason not doing "simba.Tables" like you have done in your code; you can surely do that if you want every table scripts to be generated. So this code generates script and store it to specified file.
Hope it helps

Thanks #Zaki Mohammed,
Your code helped me a lot,
I just modify a bit for my case and it works perfectly,
Server serv = new Server(db);
Database simba = serv.Databases[dbname];
Scripter scripter = new Scripter(serv);
scripter.Options.FileName = "InsertIntoScript.sql";
scripter.Options.EnforceScriptingOptions = true;
scripter.Options.WithDependencies = false;
scripter.Options.IncludeHeaders = true;
scripter.Options.ScriptDrops = false;
scripter.Options.AppendToFile = true;
scripter.Options.ScriptSchema = false;
scripter.Options.ScriptData = true;
scripter.Options.Indexes = false;
string script = "";
foreach (Table tb in simba.Tables)
{
if (tables.Contains(tb.Name))
{
IEnumerable<string> sc = scripter.EnumScript(new Urn[] { tb.Urn });
foreach (var s in sc)
script += s;
}
}

Related

Lucene 4.8 facets usage

I have difficulties understanding this example on how to use facets :
https://lucenenet.apache.org/docs/4.8.0-beta00008/api/Lucene.Net.Demo/Lucene.Net.Demo.Facet.SimpleFacetsExample.html
My goal is to create an index in which each document field have a facet, so that at search time i can choose which facets use to navigate data.
What i am confused about is setup of facets in index creation, to
summarize my question : is index with facets compatibile with
ReferenceManager?
Need DirectoryTaxonomyWriter to be actually written and persisted
on disk or it will embedded into the index itself and is just
temporary? I mean given the code
indexWriter.AddDocument(config.Build(taxoWriter, doc)); of the
example i expect it's temporary and will be embedded into the index (but then the example also show you need the Taxonomy to drill down facet). So can the Taxonomy be tangled in some way with the index so that the are handled althogeter with ReferenceManager?
If is not may i just use the same folder i use for storing index?
Here is a more detailed list of point that confuse me :
In my scenario i am indexing the document asyncrhonously (background process) and then fetching the indext ASAP throught ReferenceManager in ASP.NET application. I hope this way to fetch the index is compatibile with DirectoryTaxonomyWriter needed by facets.
Then i modified the code i write introducing the taxonomy writer as indicated in the example, but i am a bit confused, seems like i can't store DirectoryTaxonomyWriter into the same folder of index because the folder is locked, need i to persist it or it will be embedded into the index (so a RAMDirectory is enougth)? if i need to persist it in a different direcotry, can i safely persist it into subdirectory?
Here the code i am actually using :
private static void BuildIndex (IndexEntry entry)
{
string targetFolder = ConfigurationManager.AppSettings["IndexFolder"] ?? string.Empty;
//** LOG
if (System.IO.Directory.Exists(targetFolder) == false)
{
string message = #"Index folder not found";
_fileLogger.Error(message);
_consoleLogger.Error(message);
return;
}
var metadata = JsonConvert.DeserializeObject<IndexMetadata>(File.ReadAllText(entry.MetdataPath) ?? "{}");
string[] header = new string[0];
List<dynamic> csvRecords = new List<dynamic>();
using (var reader = new StreamReader(entry.DataPath))
{
CsvConfiguration csvConfiguration = new CsvConfiguration(CultureInfo.InvariantCulture);
csvConfiguration.AllowComments = false;
csvConfiguration.CountBytes = false;
csvConfiguration.Delimiter = ",";
csvConfiguration.DetectColumnCountChanges = false;
csvConfiguration.Encoding = Encoding.UTF8;
csvConfiguration.HasHeaderRecord = true;
csvConfiguration.IgnoreBlankLines = true;
csvConfiguration.HeaderValidated = null;
csvConfiguration.MissingFieldFound = null;
csvConfiguration.TrimOptions = CsvHelper.Configuration.TrimOptions.None;
csvConfiguration.BadDataFound = null;
using (var csvReader = new CsvReader(reader, csvConfiguration))
{
csvReader.Read();
csvReader.ReadHeader();
csvReader.Read();
header = csvReader.HeaderRecord;
csvRecords = csvReader.GetRecords<dynamic>().ToList();
}
}
string targetDirectory = Path.Combine(targetFolder, "Index__" + metadata.Boundle + "__" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + "__" + Path.GetRandomFileName().Substring(0, 6));
System.IO.Directory.CreateDirectory(targetDirectory);
//** LOG
{
string message = #"..creating index : {0}";
_fileLogger.Information(message, targetDirectory);
_consoleLogger.Information(message, targetDirectory);
}
using (var dir = FSDirectory.Open(targetDirectory))
{
using (DirectoryTaxonomyWriter taxoWriter = new DirectoryTaxonomyWriter(dir))
{
Analyzer analyzer = metadata.GetAnalyzer();
var indexConfig = new IndexWriterConfig(LuceneVersion.LUCENE_48, analyzer);
using (IndexWriter writer = new IndexWriter(dir, indexConfig))
{
long entryNumber = csvRecords.Count();
long index = 0;
long lastPercentage = 0;
foreach (dynamic csvEntry in csvRecords)
{
Document doc = new Document();
IDictionary<string, object> dynamicCsvEntry = (IDictionary<string, object>)csvEntry;
var indexedMetadataFiled = metadata.IdexedFields;
foreach (string headField in header)
{
if (indexedMetadataFiled.ContainsKey(headField) == false || (indexedMetadataFiled[headField].NeedToBeIndexed == false && indexedMetadataFiled[headField].NeedToBeStored == false))
continue;
var field = new Field(headField,
((string)dynamicCsvEntry[headField] ?? string.Empty).ToLower(),
indexedMetadataFiled[headField].NeedToBeStored ? Field.Store.YES : Field.Store.NO,
indexedMetadataFiled[headField].NeedToBeIndexed ? Field.Index.ANALYZED : Field.Index.NO
);
doc.Add(field);
var facetField = new FacetField(headField, (string)dynamicCsvEntry[headField]);
doc.Add(facetField);
}
long percentage = (long)(((decimal)index / (decimal)entryNumber) * 100m);
if (percentage > lastPercentage && percentage % 10 == 0)
{
_consoleLogger.Information($"..indexing {percentage}%..");
lastPercentage = percentage;
}
writer.AddDocument(doc);
index++;
}
writer.Commit();
}
}
}
//** LOG
{
string message = #"Index Created : {0}";
_fileLogger.Information(message, targetDirectory);
_consoleLogger.Information(message, targetDirectory);
}
}

How to set column Properties in SQL Server

I have to create a Copy of a Database on SQL Server.
On this way I got a connection to the new DB
ADODB.Connection connection = new ADODB.Connection();
OleDbConnectionStringBuilder builder = new System.Data.OleDb.OleDbConnectionStringBuilder();
builder["Provider"] = provider;
builder["Server"] = #"Themis\DEV";
builder["Database"] = file_name;
builder["Integrated Security"] = "SSPI";
string connection_string = builder.ConnectionString;
connection.Open(connection_string, null, null, 0);
return connection;
}
I create the tables with ADOX
ADOX.Catalog cat, Dictionary<string, ADOX.DataTypeEnum> columntype)
{
List<string> primaryKeysList = GetPrimaryKey(tabelle);
Key priKey = new Key();
Catalog catIn = new Catalog();
catIn.ActiveConnection = dbInfo.ConIn;
Dictionary<string, List<string>> indexinfo = new Dictionary<string, List<string>>();
GetSecondaryIndex(tabelle, indexinfo);
if (columntype.Count != 0) columntype.Clear();
if (size.Count != 0) size.Clear();
foreach (DataRow myField in schemaTable.Rows)
{
String columnNameValue = myField[columnName].ToString(); //SpaltenName
bool ich_darf_dbnull_sein = (bool)myField["AllowDBNull"];
ADOX.Column columne = new ADOX.Column();
columne.ParentCatalog = cat;
columne.Name = columnNameValue;
if (!columntype.ContainsKey(columnNameValue))
{
columntype.Add(columnNameValue, (ADOX.DataTypeEnum)myField["ProviderType"]);
}
columne.Type = (ADOX.DataTypeEnum)myField["ProviderType"];
//type.Add((ADODB.DataTypeEnum)myField["ProviderType"]);
columne.DefinedSize = (int)myField["ColumnSize"];
dbInfo.ColumnName = columnNameValue;
dbInfo.TableName = tabelle;
dbInfo.Column_size = (int)myField["ColumnSize"];
dbInfo.Column_Type = (ADOX.DataTypeEnum)myField["ProviderType"];
size.Add((int)myField["ColumnSize"]);
if (primaryKeysList.Contains(columnNameValue))
{
dbInfo.IsPrimary = true;
}
else dbInfo.IsPrimary = false;
object index = catIn.Tables[tabelle].Columns[columnNameValue].Attributes;
if (index.Equals(ColumnAttributesEnum.adColFixed) || (int)index == 3)
dbInfo.Fixed_length = true;
else
dbInfo.Fixed_length = false;
Console.WriteLine("{0}={1}", myField[columnName].ToString(), catIn.Tables[tabelle].Columns[columnNameValue].Attributes);
TargetDBMS.SetColumnProperties(columne, dbInfo);
switch (columne.Type)
{
case ADOX.DataTypeEnum.adChar:
case ADOX.DataTypeEnum.adWChar:
case ADOX.DataTypeEnum.adVarChar:
case ADOX.DataTypeEnum.adVarWChar:
columne.DefinedSize = (int)myField["ColumnSize"];
break;
default:
break;
}
if (primaryKeysList.Contains(columnNameValue))
{
priKey.Name = "PK_" + tabelle + "_" + columnNameValue;
primaryKeysList.Remove(columnNameValue);
priKey.Columns.Append(myField[columnName], (ADOX.DataTypeEnum)myField["ProviderType"], (int)myField["ColumnSize"]);
}
columnNameList.Add(columnNameValue);
table.Columns.Append(columne);
}
table.Keys.Append((object)priKey, KeyTypeEnum.adKeyPrimary);
}
But when I set the Properties for the columns I got an Exception
internal override void SetColumnProperties(ADOX.Column columne, DbInfo dbInfo)
{
GetColumnProperties(dbInfo);
columne.Properties["Autoincrement"].Value = dbInfo.Field_prop["Autoincrement"];
columne.Properties["Default"].Value = dbInfo.Field_prop["Default"];
columne.Properties["Nullable"].Value = dbInfo.Field_prop["Nullable"];
}
My Program works well for Access DB, but I cannot set it for the DB on SQL Server
Exception (0x80040E21) Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done.
If I try this way
string query = "SELECT * FROM Forms";
DataTable dt = new DataTable();
using (SqlConnection sqlConn = Connection())
using (SqlCommand cmd = new SqlCommand(query, sqlConn))
{
sqlConn.Open();
dt.Load(cmd.ExecuteReader());
}
foreach (DataColumn col in dt.Columns)
{
Console.WriteLine(col.ColumnName);
col.AllowDBNull = true;
dt.AcceptChanges();
col.AutoIncrement = false;
dt.AcceptChanges();
}
it does not change the properties in the DB
The Problem is partially solved
columne.Properties["Autoincrement"].Value = (bool)dbInfo.Autoincrement;
because the dbInfo.Autoincrement was an object I have to write (bool) dbInfo.Autoincrement
Not solved is this
columne.Properties["Default"].Value = (string)dbInfo.Default_Value;
because the type of a value Default_Value can be 0, empty ("") or "-"...I don’t know what i can do in this case

How to generate mdx query using C#?

I am new to mdx query and I am very curious about mdx query generation using C# so I searched for any demo or open source then I found Ranet.olap (https://ranetuilibraryolap.codeplex.com/) which is providing what I need.
After taking the dlls I tried to incorporate them in my code. I am pasting my full console code which should generate mdx query but it's not doing so, am I doing something wrong?
using System;
using System.Collections.Generic;
using Microsoft.AnalysisServices.AdomdClient;
using Ranet.Olap.Core.Managers;
using Ranet.Olap.Core.Metadata;
using Ranet.Olap.Core.Types;
namespace MDX
{
class Program
{
static void Main(string[] args)
{
startWork();
}
public static void startWork()
{
string connString = "Provider=MSOLAP.3; Data Source=localhost;Initial Catalog=AdventureWorkDW2008R2;Integrated Security=SSPI;";
CubeDef cubes;
AdomdConnection conn = new AdomdConnection(connString);
conn.Open();
cubes = conn.Cubes.Find("AdventureWorkCube");
Ranet.Olap.Core.Managers.MdxQueryBuilder mdx = new Ranet.Olap.Core.Managers.MdxQueryBuilder();
mdx.Cube = cubes.Caption;
List<Ranet.Olap.Core.Wrappers.AreaItemWrapper> listColumn = new List<Ranet.Olap.Core.Wrappers.AreaItemWrapper>();
List<Ranet.Olap.Core.Wrappers.AreaItemWrapper> listRow = new List<Ranet.Olap.Core.Wrappers.AreaItemWrapper>();
List<Ranet.Olap.Core.Wrappers.AreaItemWrapper> listData = new List<Ranet.Olap.Core.Wrappers.AreaItemWrapper>();
//Column area
Dimension dmColumn = cubes.Dimensions.Find("Dim Product");
Microsoft.AnalysisServices.AdomdClient.Hierarchy hColumn = dmColumn.Hierarchies["English Product Name"];
//hierarchy properties
List<PropertyInfo> lPropInfo = new List<PropertyInfo>();
foreach (var prop in hColumn.Properties)
{
PropertyInfo p = new PropertyInfo();
p.Name = prop.Name;
p.Value = prop.Value;
lPropInfo.Add(p);
}
Ranet.Olap.Core.Wrappers.AreaItemWrapper areaIColumn = new Ranet.Olap.Core.Wrappers.AreaItemWrapper();
areaIColumn.AreaItemType = AreaItemWrapperType.Hierarchy_AreaItemWrapper;
areaIColumn.Caption = hColumn.Caption;
areaIColumn.CustomProperties = lPropInfo;
listColumn.Add(areaIColumn);
//Rows Area
Dimension dmRow = cubes.Dimensions.Find("Due Date");
Microsoft.AnalysisServices.AdomdClient.Hierarchy hRow = dmRow.Hierarchies["English Month Name"];
List<PropertyInfo> lRowPropInfo = new List<PropertyInfo>();
foreach (var prop in hRow.Properties)
{
PropertyInfo p = new PropertyInfo(prop.Name,prop.Value);
lRowPropInfo.Add(p);
}
Ranet.Olap.Core.Wrappers.AreaItemWrapper areaIRow = new Ranet.Olap.Core.Wrappers.AreaItemWrapper();
areaIRow.AreaItemType = AreaItemWrapperType.Hierarchy_AreaItemWrapper;
areaIRow.Caption = hRow.Caption;
areaIRow.CustomProperties = lRowPropInfo;
listRow.Add(areaIRow);
//Measure Area or Data Area
Measure ms = cubes.Measures.Find("Order Quantity");
Ranet.Olap.Core.Wrappers.AreaItemWrapper areaIData = new Ranet.Olap.Core.Wrappers.AreaItemWrapper();
areaIData.AreaItemType = AreaItemWrapperType.Measure_AreaItemWrapper;
areaIData.Caption = ms.Caption;
List<PropertyInfo> lmpropInfo = new List<PropertyInfo>();
foreach (var prop in ms.Properties)
{
PropertyInfo p = new PropertyInfo(prop.Name, prop.Value);
lmpropInfo.Add(p);
}
areaIData.CustomProperties = lmpropInfo;
listData.Add(areaIData);
mdx.AreaWrappersColumns = listColumn;
mdx.AreaWrappersRows = listRow;
mdx.AreaWrappersData = listData;
string mdxQuery = mdx.GenerateMdxQuery();
conn.Close();
}
}
}
A simple example of the generation mdx query (only Ranet OLAP 3.7 version):
using System.Collections.Generic;
using Ranet.Olap.Core.Data;
using Ranet.Olap.Core.Managers;
using Ranet.Olap.Core.Types;
using Ranet.Olap.Core.Wrappers;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
startWork();
}
public static void startWork()
{
var mdx = new QueryBuilderParameters
{
CubeName = "[Adventure Works]",
SubCube = "",
MdxDesignerSetting = new MDXDesignerSettingWrapper(),
CalculatedMembers = new List<CalcMemberInfo>(),
CalculatedNamedSets = new List<CalculatedNamedSetInfo>(),
AreaWrappersFilter = new List<AreaItemWrapper>(),
AreaWrappersColumns = new List<AreaItemWrapper>(),
AreaWrappersRows = new List<AreaItemWrapper>(),
AreaWrappersData = new List<AreaItemWrapper>()
};
//define parameters
mdx.MdxDesignerSetting.HideEmptyColumns = false;
mdx.MdxDesignerSetting.HideEmptyRows = false;
mdx.MdxDesignerSetting.UseVisualTotals = false;
mdx.MdxDesignerSetting.SubsetCount = 0;
var itemCol1 = new Hierarchy_AreaItemWrapper
{
AreaItemType = AreaItemWrapperType.Hierarchy_AreaItemWrapper,
UniqueName = "[Customer].[Customer Geography]"
};
mdx.AreaWrappersColumns.Add(itemCol1);
var itemRow1 = new Hierarchy_AreaItemWrapper
{
AreaItemType = AreaItemWrapperType.Hierarchy_AreaItemWrapper,
UniqueName = "[Date].[Calendar]"
};
mdx.AreaWrappersRows.Add(itemRow1);
var itemData1 = new Measure_AreaItemWrapper();
itemData1.AreaItemType = AreaItemWrapperType.Measure_AreaItemWrapper;
itemData1.UniqueName = "[Measures].[Internet Order Count]";
mdx.AreaWrappersData.Add(itemData1);
string query = MdxQueryBuilder.Default.BuildQuery(mdx, null);
}
}
}
MDX Query result:
SELECT
HIERARCHIZE(HIERARCHIZE([Customer].[Customer Geography].Levels(0).Members)) DIMENSION PROPERTIES PARENT_UNIQUE_NAME, HIERARCHY_UNIQUE_NAME, CUSTOM_ROLLUP, UNARY_OPERATOR, KEY0 ON 0,
HIERARCHIZE(HIERARCHIZE([Date].[Calendar].Levels(0).Members)) DIMENSION PROPERTIES PARENT_UNIQUE_NAME, HIERARCHY_UNIQUE_NAME, CUSTOM_ROLLUP, UNARY_OPERATOR, KEY0 ON 1
FROM
[Adventure Works]
WHERE ([Measures].[Internet Order Count])
CELL PROPERTIES BACK_COLOR, CELL_ORDINAL, FORE_COLOR, FONT_NAME, FONT_SIZE, FONT_FLAGS, FORMAT_STRING, VALUE, FORMATTED_VALUE, UPDATEABLE, ACTION_TYPE
Still in process of revising code for this engine, though some suggestions for you:
It looks like you just grab cube metadata (dims, measures etc.) and pass it to generator. This does not sound like a way to generate MDX. MDX statement should look like
select
{
// measures, calculated members
} on 0,
{
// dimension data - sets
} on 1 // probably more axis
from **Cube**
All other parameters are optional

Remove records from Database that are not in a flat file

I'm importing records from a text file into my DB. I have it setup to check the record that I to ensure there is not already a duplicate in the database. If there is already an entry in the database it skips that record.
Now the issue I need to address is when there is not a record in the text file but there is a record in the database. I need to remove the record from the database that does not match any records in the file.
public static void ParseComplaint(string location)
{
Console.WriteLine("Parsing.....");
List<AutoMakeNoEntity> am = DBCacheHelper.GetAllMakes().ToList<AutoMakeNoEntity>();
using (var reader = new StreamReader(location))
{
foreach (string line in File.ReadLines(location))
{
if (string.IsNullOrWhiteSpace(line))
{
continue;
}
var tokens = line.Trim().Split(new char[] { '\t' });
if (am.Any(c => c.MakeName == tokens[3]))
{
using (RecallsContext context = new RecallsContext())
{
string tmp = tokens[0];
if (!context.complaints.Any(c => c.CMPLID == tmp))
{
var recalls = new Complaints();
recalls.CMPLID = tokens[0];
recalls.ODINO = tokens[1];
recalls.MFR_NAME = tokens[2];
recalls.MAKETXT = tokens[3];
recalls.MODELTXT = tokens[4];
recalls.YEARTXT = tokens[5];
recalls.CRASH = tokens[6];
recalls.FAILDATE = tokens[7];
recalls.FIRE = tokens[8];
recalls.INJURED = tokens[9];
recalls.DEATHS = tokens[10];
recalls.COMPDESC = tokens[11];
recalls.CITY = tokens[12];
recalls.STATE = tokens[13];
recalls.VIN = tokens[14];
recalls.DATEA = tokens[15];
recalls.LDATE = tokens[16];
recalls.MILES = tokens[17];
recalls.OCCURENCES = tokens[18];
recalls.CDESCR = tokens[19];
recalls.CMPL_TYPE = tokens[20];
recalls.POLICE_RPT_YN = tokens[21];
recalls.PURCH_DT = tokens[22];
recalls.ORIG_OWNER_YN = tokens[23];
recalls.ANTI_BRAKES_YN = tokens[24];
recalls.CRUISE_CONT_YN = tokens[25];
recalls.NUM_CYLS = tokens[26];
recalls.DRIVE_TRAIN = tokens[27];
recalls.FUEL_SYS = tokens[28];
recalls.FUEL_TYPE = tokens[29];
recalls.TRANS_TYPE = tokens[30];
recalls.VEH_SPEED = tokens[31];
recalls.DOT = tokens[32];
recalls.TIRE_SIZE = tokens[33];
recalls.LOC_OF_TIRE = tokens[34];
recalls.TIRE_FAIL_TYPE = tokens[35];
recalls.ORIG_EQUIP_YN = tokens[36];
recalls.MANUF_DT = tokens[37];
recalls.SEAT_TYPE = tokens[38];
recalls.RESTRAINT_TYPE = tokens[39];
recalls.DEALER_NAME = tokens[40];
recalls.DEALER_TEL = tokens[41];
recalls.DEALER_CITY = tokens[42];
recalls.DEALER_STATE = tokens[43];
recalls.DEALER_ZIP = tokens[44];
recalls.PROD_TYPE = tokens[45];
if (tokens.Length == 47)
{
recalls.REPAIRED_YN = tokens[46];
}
context.complaints.Add(recalls);
context.SaveChanges();
recalls.Dispose();
}
}
}
}
}
}
I need to remove the record from the database that does not match any records in the file.
If you want the database to match the contents of the text file, why don't you simply empty it first?

How to convert a FullTextSqlQuery result to an SPListItem?

I though the following code would work but every time I look at file.Item; it is null. Should I be doing something different?
Microsoft.Office.Server.Search.Query.FullTextSqlQuery query = new Microsoft.Office.Server.Search.Query.FullTextSqlQuery(siteCollection);
query.QueryText = "SELECT Title, Path, Description, Write, Rank, Size from scope() where \"scope\" = 'SocialNetworking'";
query.ResultTypes = Microsoft.Office.Server.Search.Query.ResultType.RelevantResults;
//query.RowLimit = Int32.MaxValue;
query.TrimDuplicates = true;
query.EnableStemming = false;
query.IgnoreAllNoiseQuery = true;
query.KeywordInclusion = Microsoft.Office.Server.Search.Query.KeywordInclusion.AllKeywords;
query.Timeout = 0x2710;
query.HighlightedSentenceCount = 3;
query.SiteContext = new Uri(siteCollection.Url);
query.AuthenticationType = Microsoft.Office.Server.Search.Query.QueryAuthenticationType.NtAuthenticatedQuery;
Microsoft.Office.Server.Search.Query.ResultTableCollection queryResults = query.Execute();
Microsoft.Office.Server.Search.Query.ResultTable queryResultsTable = queryResults[Microsoft.Office.Server.Search.Query.ResultType.RelevantResults];
DataTable queryDataTable = new DataTable();
queryDataTable.Load(queryResultsTable, LoadOption.OverwriteChanges);
foreach (DataRow dr in queryDataTable.Rows)
{
//if (dr["ContentType"].ToString() == "Item")
//{
using (SPSite lookupSite = new SPSite(dr["Path"].ToString()))
{
using (SPWeb web = lookupSite.OpenWeb())
{
SPFile file = web.GetFile(dr["Path"].ToString());
SPListItem li = file.Item;
}
}
//}
}
If you know it is an item try SPWeb.GetListItem
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spweb.getlistitem.aspx
The file might also not exist, check SPFile.Exists before using any of SPFile's properties
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spfile.exists.aspx

Categories

Resources