How can get result from OleDbDataReader with C# method - c#

How can return this from method ????
this is important for me
thank
this is my method :
public static dynamic GetFactorProperties(int factornumber)
{
using (var db = new OleDbConnection(cs))
{
db.Open();
var cmd = new OleDbCommand("SELECT * FROM FactorList WHERE FactorNumber = #0", db);
cmd.Parameters.AddWithValue("#0", factornumber);
var result = cmd.ExecuteReader();
if(result.Read())
{
return result ;
}
else
{
return ProperiesObject();
}
}
}
and this is my ExpandoObject()
public static dynamic ProperiesObject()
{
dynamic obj = new ExpandoObject();
obj.FactorDate = string.Empty;
obj.FactorNumber = string.Empty;
obj.CustomerName = string.Empty;
obj.FactorPrice = string.Empty;
obj.Discount = string.Empty;
return obj;
}
and this is read from method source :
var result = Program.GetFactorProperties(factornumber);
TXTDate.Text = result.FactorDate;
TXTFactorNumber.Text = result.FactorNumber;
TXTCustomerName.Text = result.CustomerName;
TXTFactorParice.Text = result.FactorPrice;
TXTDiscount.Text = result.Discount;

Method should look like this:
public static dynamic GetFactorProperties(int factornumber)
{
using (var db = new OleDbConnection(cs))
{
db.Open();
var cmd = new OleDbCommand("SELECT * FROM FactorList WHERE FactorNumber = #0", db);
cmd.Parameters.AddWithValue("#0", factornumber);
var result = cmd.ExecuteReader();
if(result.Read())
{
dynamic obj = new ExpandoObject();
obj.FactorDate = result.GetString(0);
obj.FactorNumber = result.GetString(1);
// ...
return obj;
}
else
{
return ProperiesObject();
}
}
}
GetString accepts number of column, from which you want to get value

Related

how to return an object in c#?

I'm filling data inside an object with c# but I don't know how to return this object.
I create an object named ArasOrder and fill in the data and I want to return the ArasOrder object.
how can I do this.
public class ArasDeneme
{
public static void aras()
{
var ArasService = new ArasTEST.Service();
var ArasGonderi = new ArasTEST.ShippingOrder();
var ArasOrder = new ArasTEST.Order();
var parametreler = ArasKargoTEST.ParametreGet();
var newentegrationcode = "";
foreach (var item in parametreler)
{
var encode = entegrationcode();
var YeniGelenDesi = DesiHesabi(item.WebSiparisNo);
var yeniteminyeri = item.TeminYeri;
newentegrationcode = 123+ "" + encode;
ArasOrder.UserName = "";
ArasOrder.Password = "";
ArasOrder.ReceiverName = item.KargoAdSoyad;
ArasOrder.ReceiverPhone1 = item.KargoTelefon;
ArasOrder.ReceiverCityName = item.KargoIlAdi;
ArasOrder.ReceiverTownName = item.KargoIlceAdi;
ArasOrder.ReceiverAddress = item.KargoAdres;
ArasOrder.TradingWaybillNumber = item.WebSiparisNo;
ArasOrder.PieceCount = "1";
ArasOrder.IntegrationCode = newentegrationcode;
ArasOrder.PayorTypeCode = "1";
ArasOrder.IsWorldWide = "0";
ArasOrder.IsCod = "0";
ArasOrder.VolumetricWeight = YeniGelenDesi;
ArasOrder.SenderAccountAddressId = "1071";
ArasTEST.PieceDetail[] ArasPieceDetails = new ArasTEST.PieceDetail[1];
PieceDetail ArasPieceDetail1 = new PieceDetail();
ArasPieceDetail1.BarcodeNumber = newentegrationcode;
ArasPieceDetail1.VolumetricWeight = YeniGelenDesi;
ArasPieceDetail1.Weight = "1";
ArasPieceDetail1.Description = "";
ArasPieceDetails[0] = ArasPieceDetail1;
ArasOrder.PieceDetails = ArasPieceDetails;
var ArasOrderInfo = new ArasTEST.Order[1];
ArasOrderInfo[0] = ArasOrder;
var takipNoResult = ArasService.SetOrder("", "", "");
var ArasOrderResultInfo = takipNoResult[0];
var SonucKodu = takipNoResult[0].ResultCode;
var SonucMesaji = takipNoResult[0].ResultMessage;
var SonucInvoiceKey = takipNoResult[0].InvoiceKey;
}
}
}
You should define the return type and return the instance.
public static ArasTEST aras()
{
// insert code here...
return ArasOrder;
}
Change void to ArasDeneme return type.
Then call like:
var ad = ArasDeneme.aras();

HangFire running each job separately

I am using HangFire to run the job. I have a method that retrieve data from more than 50 sql servers.
I want to use HangFire to run each location separately by LocationID, and if 1 location fails I want that job get running again for that location after x minutes.
Also I want to see the log of the job on the HangFire Dashboard.
My job method :
public void SyncCompInfo()
{
List<Location> locations;
using (var db = new CompInfoDemoEntities())
{
locations = db.Locations.Where(x => x.IsActive).ToList();
}
foreach (var location in locations)
{
try
{
using (var _db = new CompInfoDemoEntities())
{
_log.Info("Getting CompoInfo data from location: " + location.StoreName);
_syncLogService.Add("Getting CompoInfo data from location: " + location.StoreName);
var responses = new List<CompInfoResponse>();
var compInfos = _db.IMS_CompInfo.Where(x => x.LocationId == location.Id).ToList();
using (var cnn = new SqlConnection(location.ConnectionString))
{
var sql = "select * from IMS_CompInfo;";
var sqlCmd = new SqlCommand(sql, cnn);
cnn.Open();
using (SqlDataReader rdr = sqlCmd.ExecuteReader())
{
while (rdr.Read())
{
var item = new CompInfoResponse();
item.Id = int.Parse(rdr["Id"].ToString());
item.ClientID = rdr["ClientID"].ToString();
item.LicenceID = rdr["LicenceID"].ToString();
item.POSCode = rdr["POSCode"].ToString();
item.logiPOS_Version = rdr["logiPOS_Version"].ToString();
if (rdr["LastLoginDate"] != null)
{
item.LastLoginDate = DateTime.Parse(rdr["LastLoginDate"].ToString());
}
item.ComputerName = rdr["ComputerName"].ToString();
if (rdr["BootTime"] != null)
{
item.BootTime = DateTime.Parse(rdr["BootTime"].ToString());
}
item.Domain = rdr["Domain"].ToString();
item.Manufacturer = rdr["Manufacturer"].ToString();
item.Model = rdr["Model"].ToString();
item.Memory = rdr["Memory"].ToString();
item.OS = rdr["OS"].ToString();
item.Build = rdr["Build"].ToString();
item.CPU = rdr["CPU"].ToString();
item.ProcArchitecture = rdr["ProcArchitecture"].ToString();
item.IP1 = rdr["IP1"].ToString();
item.MAC1 = rdr["MAC1"].ToString();
if (rdr["LastModifiedDate"] != null)
{
item.LastModifiedDate = DateTime.Parse(rdr["LastModifiedDate"].ToString());
}
if (rdr["Tag"] != null)
{
item.Tag = int.Parse(rdr["Tag"].ToString());
}
item.Application = rdr["Application"].ToString();
responses.Add(item);
}
}
}
What you seem to need is something like this, with a method you call upon startup, which loops other the locations and enqueues a job for each location.
I over simplified the thing (for example making the methods static),
but I guess most of the idea is there.
Have a look at Hangfire recurring tasks I guess it may be better suited to your needs than tasks fired upon application startups.
public void CalledUponStartup()
{
List<Location> locations;
using (var db = new CompInfoDemoEntities())
{
locations = db.Locations.Where(x => x.IsActive).ToList();
}
foreach (var location in locations)
{
BackgroundJob.Enqueue(() => SyncCompInfo(location.Id));
}
}
public static void SyncCompInfo(int locationId)
{
try
{
using (var _db = new CompInfoDemoEntities())
{
var location = db.Locations.FirstOrDefault(x => x.Id == locationId);
_log.Info("Getting CompoInfo data from location: " + location.StoreName);
_syncLogService.Add("Getting CompoInfo data from location: " + location.StoreName);
var responses = new List<CompInfoResponse>();
var compInfos = _db.IMS_CompInfo.Where(x => x.LocationId == location.Id).ToList();
using (var cnn = new SqlConnection(location.ConnectionString))
{
var sql = "select * from IMS_CompInfo;";
var sqlCmd = new SqlCommand(sql, cnn);
cnn.Open();
using (SqlDataReader rdr = sqlCmd.ExecuteReader())
{
while (rdr.Read())
{
var item = new CompInfoResponse();
item.Id = int.Parse(rdr["Id"].ToString());
item.ClientID = rdr["ClientID"].ToString();
item.LicenceID = rdr["LicenceID"].ToString();
item.POSCode = rdr["POSCode"].ToString();
item.logiPOS_Version = rdr["logiPOS_Version"].ToString();
if (rdr["LastLoginDate"] != null)
{
item.LastLoginDate = DateTime.Parse(rdr["LastLoginDate"].ToString());
}
item.ComputerName = rdr["ComputerName"].ToString();
if (rdr["BootTime"] != null)
{
item.BootTime = DateTime.Parse(rdr["BootTime"].ToString());
}
item.Domain = rdr["Domain"].ToString();
item.Manufacturer = rdr["Manufacturer"].ToString();
item.Model = rdr["Model"].ToString();
item.Memory = rdr["Memory"].ToString();
item.OS = rdr["OS"].ToString();
item.Build = rdr["Build"].ToString();
item.CPU = rdr["CPU"].ToString();
item.ProcArchitecture = rdr["ProcArchitecture"].ToString();
item.IP1 = rdr["IP1"].ToString();
item.MAC1 = rdr["MAC1"].ToString();
if (rdr["LastModifiedDate"] != null)
{
item.LastModifiedDate = DateTime.Parse(rdr["LastModifiedDate"].ToString());
}
if (rdr["Tag"] != null)
{
item.Tag = int.Parse(rdr["Tag"].ToString());
}
item.Application = rdr["Application"].ToString();
responses.Add(item);
}
}

How to change decimal separator in ExecuteReader c#

How to change decimal separator in string, e.g. in mnoz_obj item the returned value is 24,000 and I need to have 24.000. The values are from database to JSON.
I tried ToString(new CultureInfo etc.) but this doesn't work. I expect that myString.Replace(",",".") is not correct way to do it.
public static string getDoklad()
{
var dbCon = ConfigurationManager.ConnectionStrings["myConn"].ConnectionString;
string[] fileArguments = Environment.GetCommandLineArgs();
List<ZebraPolozky> zebraPolozky = new List<ZebraPolozky>();
using (var cn = new OdbcConnection(dbCon))
{
OdbcCommand cmd = cn.CreateCommand();
cmd.CommandText = "SELECT * FROM cis06zebrap";
cn.Open();
using (var reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
ZebraPolozky zebraPolozka = new ZebraPolozky
{
doklad = reader["doklad"].ToString(),
sklad = reader["sklad"].ToString(),
reg = reader["reg"].ToString(),
mnoz_obj = reader["mnoz_obj"].ToString(),
mnoz_vyd = reader["mnoz_vyd"].ToString(),
kc_pce = reader["kc_pce"].ToString(),
sarze = reader["sarze"].ToString(),
datspo = reader["datspo"].ToString(),
veb = reader["veb"].ToString(),
poc2 = reader["poc2"].ToString(),
pvp06pk = reader["pvp06pk"].ToString(),
znacky = reader["znacky"].ToString(),
stav = reader["stav"].ToString(),
//prac = reader["prac"].ToString(),
//exp = reader["exp"].ToString()
};
zebraPolozky.Add(zebraPolozka);
}
}
}
cn.Close();
}
//var collw = new { polozky = zebraPolozky };
var jsonString = JsonConvert.SerializeObject(zebraPolozky);
return jsonString;
}
{
"doklad": "568375",
"sklad": "901",
"reg": "185121",
"mnoz_obj": "24,000",
"mnoz_vyd": "0,000",
"kc_pce": "240,72",
"sarze": "",
"datspo": "",
"veb": "24,00",
"poc2": "1",
"pvp06pk": "116783437",
"znacky": "R1902",
"stav": "0"
}
OdbcDataReader gives the value in its native format as stated in the doc.
You should then be able to cast it and use the overload of .ToString() you need.
Try something like:
((decimal)reader["mnoz_obj"]).ToString("N2")

elasticsearch speed comparison issue with sql

I compare the speed of Sql with ElasticSearch. I have 1.5 million data. But sql query runs faster than elastic search. I don't understand the problem.
Why is the word like query coming faster in sql?
My code for Sql
public static List<Sales> GetAllRecords(string itemType)
{
List<Sales> salesReports = new List<Sales>();
string sqlQuery = String.Format(#"SELECT * FROM dbo.Sales where Region like '%{0}%'", itemType);
using (SqlConnection connection = new SqlConnection(CONNECTION_STRING))
{
var result = connection.Query<Sales>(sqlQuery);
foreach (var item in result)
{
Sales global = new Sales()
{
Region = item.Region,
Country = item.Country,
Item_Type=item.Item_Type,
Order_Date=item.Order_Date,
Order_ID = item.Order_ID,
Order_Priority=item.Order_Priority,
Sales_Channel=item.Sales_Channel,
Ship_Date = item.Ship_Date,
Total_Cost=item.Total_Cost,
Total_Profit=item.Total_Profit,
Total_Revenue=item.Total_Revenue,
Units_Sold=item.Units_Sold,
Unit_Cost=item.Unit_Cost,
Unit_Price = item.Unit_Price
};
salesReports.Add(global);
}
return result.ToList();
}
}
My code for ElasticSearch.
I search the data that I indexed before with elasticsearch here.
public static List<Sales> ConfigureES(string inputText)
{
List<Sales> salesReports = new List<Sales>();
// 1. Connection URL's elastic search
var listOfUrls = new Uri[]
{
// here we can set multple connectionn URL's...
new Uri("http://localhost:9200/")
};
StaticConnectionPool connPool = new StaticConnectionPool(listOfUrls);
ConnectionSettings connSett = new ConnectionSettings(connPool);
ElasticClient eClient = new ElasticClient(connSett);
// var see = eClient.DeleteIndex(INDEX_NAME);
// check the connection health
var checkClusterHealth = eClient.ClusterHealth();
if (checkClusterHealth.ApiCall.Success && checkClusterHealth.IsValid)
{
// 2. check the index exist or not
var checkResult = eClient.IndexExists(INDEX_NAME);
if (!checkResult.Exists)
{
// Raise error to Index not avaliable
}
// Search particular text field
var searchResponse = eClient.Search<Sales>(s =>
s.Index(INDEX_NAME).From(0).Size(5000).Scroll("10m")
.Query(q => q.Match(m => m.Field(f => f.Region).Query(inputText))));
//var results = eClient.Scroll<Salesreport>("10m", searchResponse.ScrollId);
while (searchResponse.Documents.Any())
{
var res = searchResponse.Documents;
var sds = res.Cast<Sales>();
salesReports.AddRange(sds);
searchResponse = eClient.Scroll<Sales>("10m", searchResponse.ScrollId);
}
}
else
{
// fail log the exception further use
var exception = checkClusterHealth.OriginalException.ToString();
var debugException = checkClusterHealth.DebugInformation.ToString();
}
return salesReports;
}
where I index data to elasticsearch.
public static string CONNECTION_STRING = string.Empty;
public static string INDEX_NAME = "elastic";
public static string INDEX_TYPE = "report4";
private static ElasticClient eClient;
static void Main(string[] args)
{
try
{
// read the config file ...
var configuration = new ConfigurationBuilder()
.SetBasePath(#"C:\Users\Celal\Desktop\ElasticSearch-master\ElasticSearch-master\ElasticSearchBGPJob\ElasticSearchBGPJob\ElasticSearchBGPJob")
.AddJsonFile("appsettings.json", false)
.Build();
CONNECTION_STRING = configuration.GetSection("DefaultConnection").Value;
if (string.IsNullOrEmpty(CONNECTION_STRING))
throw new ArgumentException("No connection string in appsettings.json");
// 1. Connection URL's elastic search
var listOfUrls =
// here we can set multple connectionn URL's...
new Uri("http://localhost:9200/");
ConnectionSettings connSett = new ConnectionSettings(listOfUrls);
eClient = new ElasticClient(connSett);
// var see = eClient.DeleteIndex(INDEX_NAME);
var createIndexDescriptor = new CreateIndexDescriptor(INDEX_NAME).Mappings(ms => ms.Map<Sales>(m => m.AutoMap()));
// check the connection health
var checkClusterHealth = eClient.ClusterHealth();
if (checkClusterHealth.ApiCall.Success && checkClusterHealth.IsValid)
{
// 2. check the index exist or not
var checkResult = eClient.IndexExists(INDEX_NAME);
if (!checkResult.Exists)
{
var createIndexResponse = eClient.CreateIndex(createIndexDescriptor);
if (createIndexResponse.ApiCall.Success && createIndexResponse.IsValid)
{
// index is created successfully....
}
else
{
// fail log the exception further use
var exception = createIndexResponse.OriginalException.ToString();
var debugException = createIndexResponse.DebugInformation.ToString();
}
}
// 3. get the last documet id of index
var lastRecordResponse = eClient.Search<Sales>(s => s
.Index(INDEX_NAME)
.Type(INDEX_TYPE)
.From(0)
.Size(1).Sort(sr => sr.Descending(f => f.Order_ID)));
if (lastRecordResponse.ApiCall.Success && lastRecordResponse.IsValid)
{
Console.WriteLine("Start " + DateTime.Now);
long salesRecordId = 0;
var listofrecords = new List<Sales>();
if (lastRecordResponse.Documents.Count >= 1)
{
var obj = lastRecordResponse.Documents;
foreach (var item in obj)
{
salesRecordId = item.Order_ID;
}
listofrecords = GetAllRecords(salesRecordId);
}
else
{
listofrecords = GetAllRecords(salesRecordId);
}
Console.WriteLine("END " + DateTime.Now);
// Insert the data into document format corresponding index...
if (listofrecords.Count > 0)
{
Console.WriteLine("===== START========= " + DateTime.Now);
BulkInsertData(listofrecords, eClient).Wait();
Console.WriteLine("===== END========= " + DateTime.Now);
}
}
else
{
// fail log the exception further use
var exception = lastRecordResponse.OriginalException.ToString();
var debugException = lastRecordResponse.DebugInformation.ToString();
}
}
else
{
// fail log the exception further use
var exception = checkClusterHealth.OriginalException.ToString();
var debugException = checkClusterHealth.DebugInformation.ToString();
}
Console.WriteLine("Hello World!");
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Console.ReadLine();
}
}
public static List<Sales> GetAllRecords(long LastSalesId)
{
List<Sales> salesReports = new List<Sales>();
string sqlQuery = String.Format(#"SELECT * FROM dbo.Sales where Order_ID > {0} ", LastSalesId);
using (SqlConnection connection = new SqlConnection(CONNECTION_STRING))
{
connection.Open();
using (SqlCommand command = new SqlCommand(sqlQuery, connection))
{
command.CommandTimeout = 1000;
using (SqlDataReader dataReader = command.ExecuteReader())
{
if (dataReader.HasRows)
{
while (dataReader.Read())
{
Sales global = new Sales()
{
Order_ID=Convert.ToInt32(dataReader["Order_ID"]),
Region=Convert.ToString(dataReader["Region"]),
Country = Convert.ToString(dataReader["Country"]),
Total_Cost = (decimal)Convert.ToDouble(dataReader["Total_Cost"]),
Total_Revenue = Convert.ToString(dataReader["Total_Revenue"]),
Item_Type = Convert.ToString(dataReader["Item_Type"])
};
salesReports.Add(global);
}
}
}
}
connection.Close();
}
return salesReports;
}
static async Task BulkInsertData(List<Sales> ListofData, ElasticClient Eclient)
{
try
{
var splitTheLargeList = ChunkBy(ListofData);
var test = splitTheLargeList.LastOrDefault();
foreach (var item in splitTheLargeList)
{
var bulkResponse = await Eclient.BulkAsync(b => b
.Index(INDEX_NAME)
// .Type(INDEX_TYPE)
.IndexMany(item));
if (bulkResponse.ApiCall.Success && bulkResponse.IsValid)
{
// success fully inserted...
}
else
{
// fail log the exception further use
var exception = bulkResponse.OriginalException.ToString();
var debugException = bulkResponse.DebugInformation.ToString();
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.InnerException.ToString());
}
}
public static List<List<T>> ChunkBy<T>(List<T> source, int chunkSize = 1000)
{
return source
.Select((x, i) => new { Index = i, Value = x })
.GroupBy(x => x.Index / chunkSize)
.Select(x => x.Select(v => v.Value).ToList())
.ToList();
}
public static IEnumerable<List<T>> SplitList<T>(List<T> ListofData, int listSize = 1000)
{
for (int i = 0; i < ListofData.Count; i += listSize)
{
yield return ListofData.GetRange(i, Math.Min(listSize, ListofData.Count - i));
}
}

how to return datatable and integer in c#

I am creating a method which returns datatable and an int value.I have create a method which returns only datatable.Please take a look on the code
public static DataTable ShutterstockSearchResults(string url)
{
int TotalCont=0;
DataTable dt = new DataTable();
try
{
//intigration using Basic Aouth with authrization headers
var request = (HttpWebRequest)WebRequest.Create(url);
var username = "SC";
var password = "SK";
string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(username + ":" + password));
request.Headers[HttpRequestHeader.Authorization] = string.Format("Basic {0}", credentials);
request.UserAgent = "MyApp 1.0";
var response = (HttpWebResponse)request.GetResponse();
using (var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
JavaScriptSerializer js = new JavaScriptSerializer();
var objText = reader.ReadToEnd();
SearchResult myojb = (SearchResult)js.Deserialize(objText, typeof(SearchResult));
TotalCount = myojb.total_count;
dt.Columns.Add("Id");
dt.Columns.Add("Discription");
dt.Columns.Add("Small_Thumb_URl");
dt.Columns.Add("Large_Thumb_URL");
dt.Columns.Add("Prieview_URL");
dt.Columns.Add("ContributorID");
dt.Columns.Add("aspect");
dt.Columns.Add("image_type");
dt.Columns.Add("is_illustration");
dt.Columns.Add("media_type");
foreach (var item in myojb.data)
{
var row = dt.NewRow();
row["ID"] = item.id;
row["Discription"] = item.description;
row["Small_Thumb_URl"] = item.assets.small_thumb.url;
row["Large_Thumb_URL"] = item.assets.large_thumb.url;
row["Prieview_URL"] = item.assets.preview.url;
row["ContributorID"] = item.contributor.id;
row["aspect"] = item.aspect;
row["image_type"] = item.image_type;
row["is_illustration"] = item.is_illustration;
row["media_type"] = item.media_type;
dt.Rows.Add(row);
}
// List<SearchResult> UserList = JsonConvert.DeserializeObject<List<SearchResult>>(objText);
// Response.Write(reader.ReadToEnd());
}
}
catch (WebException ea)
{
Console.WriteLine(ea.Message);
using (var stream = ea.Response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
Console.WriteLine(reader.ReadToEnd());
}
}
return dt;
}
I want to return datatable and TotalCont.please help
Generally speaking, a method can only return one type.
You have two options:
1) Create a class that has a DataTable and an int field, such as:
public class MyReturnType
{
public DataTable TheDataTable {get; set;}
public int TotalCount {get; set;}
}
And return this type from your method.
2) You can add an out parameter to your method:
public static DataTable ShutterstockSearchResults(string url, out totalCount)
And assign to totalCount within your method.
public static Tuple<DataTable, int> ShutterstockSearchResults(string url)
{
[...]
return new Tuple<DataTable, int>(dt, totalCount);
}
public static void SomeConsumerMethod()
{
var result = ShutterstockSearchResults(myPath);
DataTable dt = result.Item1;
int totalCount = result.Item2;
}
To answer the comments in Klaus answer:
public class MyReturnType
{
public DataTable TheDataTable {get; set;}
public int TotalCount {get; set;}
}
and in your method:
public static MyReturnType ShutterstockSearchResults(string url)
{
MyReturnType result=new MyReturnType();
int TotalCont=0;
DataTable dt = new DataTable();
try
{
//intigration using Basic Aouth with authrization headers
var request = (HttpWebRequest)WebRequest.Create(url);
var username = "SC";
var password = "SK";
string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(username + ":" + password));
request.Headers[HttpRequestHeader.Authorization] = string.Format("Basic {0}", credentials);
request.UserAgent = "MyApp 1.0";
var response = (HttpWebResponse)request.GetResponse();
using (var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
JavaScriptSerializer js = new JavaScriptSerializer();
var objText = reader.ReadToEnd();
SearchResult myojb = (SearchResult)js.Deserialize(objText, typeof(SearchResult));
TotalCount = myojb.total_count;
dt.Columns.Add("Id");
dt.Columns.Add("Discription");
dt.Columns.Add("Small_Thumb_URl");
dt.Columns.Add("Large_Thumb_URL");
dt.Columns.Add("Prieview_URL");
dt.Columns.Add("ContributorID");
dt.Columns.Add("aspect");
dt.Columns.Add("image_type");
dt.Columns.Add("is_illustration");
dt.Columns.Add("media_type");
foreach (var item in myojb.data)
{
var row = dt.NewRow();
row["ID"] = item.id;
row["Discription"] = item.description;
row["Small_Thumb_URl"] = item.assets.small_thumb.url;
row["Large_Thumb_URL"] = item.assets.large_thumb.url;
row["Prieview_URL"] = item.assets.preview.url;
row["ContributorID"] = item.contributor.id;
row["aspect"] = item.aspect;
row["image_type"] = item.image_type;
row["is_illustration"] = item.is_illustration;
row["media_type"] = item.media_type;
dt.Rows.Add(row);
}
// List<SearchResult> UserList = JsonConvert.DeserializeObject<List<SearchResult>>(objText);
// Response.Write(reader.ReadToEnd());
}
}
catch (WebException ea)
{
Console.WriteLine(ea.Message);
using (var stream = ea.Response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
Console.WriteLine(reader.ReadToEnd());
}
}
result.TheDataTable=dt;
result.TotalCount=TotalCount;
return result:
}
Your method needs an additional out parameter if you want to "return" more than one value. Just pass an uninitialized variable of the desired type into your method and assign that variable inside.
public void Test()
{
int i;
DataTable ShutterstockSearchResults("Some string", out i);
}
your ShutterstockSearchResults method needs to be modified accordingly:
public static DataTable ShutterstockSearchResults(string url, out int outParam)
{
outParam = 10;
// do other stuff
}
If you do not change outParam any further inside ShutterstockSearchResults, it will have the value 10 after returning to Test.
You can accomplish this with a Tuple. Consider the following simple example:
public class EmptyClass
{
public static void Main(){
EmptyClass something = new EmptyClass ();
Tuple<String, int> tuple = something.returnMe ();
Console.WriteLine ("Item 1: " + tuple.Item1);
Console.WriteLine ("Item 2: " + tuple.Item2);
}
public EmptyClass ()
{
}
public Tuple<String, int> returnMe() {
return Tuple.Create ("Hello", 2);
}
}

Categories