کار با Cursor در SQL با یک مثال ساده
در این مثال سعی کردیم که ساختار Cursor را نمایش دهیم و اطلاعاتی را از جدولی از دیتابیس به نمایش در آوریم
DECLARE @id1 INT;
DECLARE @n1 NVARCHAR(50);
DECLARE @cur CURSOR
SET @cur=CURSOR FOR SELECT RangeId,RangeName FROM dbo.Range
OPEN @cur;
FETCH NEXT FROM @cur INTO @id1,@n1;
WHILE @@FETCH_STATUS=0
BEGIN
PRINT CAST(@id1 AS NVARCHAR(50))+' '+@n1
FETCH NEXT FROM @cur INTO @id1,@n1
END
CLOSE @cur
DEALLOCATE @cur
توضیحات کامل این مقاله را در سایت پروژه چی بخوانید
نحوه نوشتن Curser بر روی دیتابیس
در این مثال قصد داریم که بر روی یک جدول از دیتابیس یک کرسر قرار دهیم که لیستی از فیلد هایی که مقدار دارند تعداد آنها را برای ما برگرداند و اسم فیلد مورد نظر را نمایش دهد.
--declare @table as table(name nvarchar(256),valuetable nvarchar(256), countValue int)
declare @name as nvarchar(256)
declare cur cursor for
select name from sys.columns where OBJECT_NAME(object_id)='Name Table' and
name not in (
'Fild1',
'Fild2',
'Fild3',
'Fild4'
)
order by name
open cur
fetch next from cur into @name
while(@@FETCH_STATUS=0)
begin
declare @str as nvarchar(4000) =' select '''+@name+''','+@name +', COUNT(*) from Name Table group by '+@name
print @str
exec(@str)
fetch next from cur into @name
end
close cur
deallocate cur
نحوه ساخت فایل زیپ در #C
در این مثال ما یک فایل تکستی داریم که آن را به فایل JSON تبدیل کرده ایم و بعد یه مجموعه عکس را از دیتابیس که فایل های آن بصورت باینری است را خوانده ایم و آن را به یک فایل زیپ تبدیل کرده ایم.و نهایتن آن را در مرورگر قابل دانلود کرده ایم
و همچنین امکان ذخیره آن نیز وجود دارد.
private void CreateZipFiles(string alljson)
{
int RegionId = Convert.ToInt32(drpRegionId.SelectedValue);
byte[] jsondata = GetBytes(alljson);
string jsonName = string.Format(RegionId.ToString() + ".json");
string zipName = string.Format(RegionId.ToString() + ".zip");
using (DAL.DataClassesDataContext Context = new DAL.DataClassesDataContext())
{
using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
{
zip.CompressionLevel = Ionic.Zlib.CompressionLevel.Level5;
var ItemAtachment = Context.ItemAttachment_FCH(null, null, RegionId).ToList();
int countid = 1;
int tempItemId = 0;
foreach (var item in ItemAtachment)
{
if (item.ItemAttachmentTypeid == 1)
{
try
{
//صاحب پروانه
Byte[] ItemImage = (Byte[])item.ItemAttachmentContent.ToArray();
jsonName = item.ItemId + "-" + "main" + ".jpg";
zip.AddEntry(jsonName, ItemImage);
}
catch
{
}
}
else if (item.ItemAttachmentTypeid == 2)
{
//سر در مشاور املاک
if (tempItemId != item.ItemId)
{
countid = 1;
}
Byte[] ItemImage = (Byte[])item.ItemAttachmentContent.ToArray();
jsonName = item.ItemId + "-" + "sub" + "-" + countid + ".jpg";
zip.AddEntry(jsonName, ItemImage);
tempItemId = item.ItemId;
countid++;
}
}
jsonName = string.Format(RegionId.ToString() + ".json");
zip.AddEntry(jsonName, jsondata);
//zip.Save(Server.MapPath(zipName));
Response.Clear();
Response.BufferOutput = false;
Response.ContentType = "application/zip";
Response.AddHeader("content-disposition", "attachment; filename=" + zipName);
zip.Save(Response.OutputStream);
Response.End();
}
}
}
// تبدیل فایل متنی به بایت
static byte[] GetBytes(string str)
{
byte[] bytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
کلیک برو روی بخشی از نقشه و ارسال اطلاعات با جی کویری
ما در این کار یک نقشه از قبل طراحی کرده بودیم و برای ارسال آیدی های آن به صفحه ی دیگر این کار را با استفاده از جی کویری انجام دادیم که کد آن را در زیر برای شما قرار داده ام
<%-- <script src="Scripts/jquery-1.7.2.min.js"></script>--%>
<%-- <script>
$(document).ready(function () {
$("map area").on('click', function () {
var $this = $(this);
var $href = $this.attr('href');
$this.attr('href', 'RequestEntry.aspx?DistrictId=' + $href);
});
});
</script>--%>
نحوه ارسال دو پارامتر به تابع با در WCF
کدها زیر را در سرویس مورد نظر می نویسیم
[OperationContract]
[WebInvoke(UriTemplate = "Invoice", RequestFormat = WebMessageFormat.Json,BodyStyle=WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json, Method = "POST")]
OutputResultStruct<KeyValuePair<string, int>> AddToInvoice(Invoice invoice, List< InvoiceDetail> invoicedetail,int RequestId);
کلاسی که برای این کار نوشتیم تا بتواند هر ساختاری را قبول کند
public class OutputResultStruct<T> where T : struct
{
public bool IsValidResult { get; set; }
public int ErrorCode { get; set; }
public string Description { get; set; }
private List<T> _resultvalue;
public List<T> resultvalue
{
get
{
return (List<T>)_resultvalue;
}
set
{
_resultvalue = value;
}
}
}
و مقدار زیر را هم در Web Config قرار می دهیم تا در هنگام آدرس دهی مشکلی نداشته باشیم
<system.serviceModel>
<services>
<endpoint address="InvoiceService" binding="webHttpBinding" contract="HamrahMelk.IInvoiceService"
behaviorConfiguration="MyEndpointBehavior" name="InvoiceService" > </endpoint>
</services>
</system.serviceModel>
حال متدی که در فایل SVC می نویسیم به شکل زیر خواهد بود.
public OutputResultStruct<KeyValuePair<string, int>> AddToInvoice(Invoice invoice, List<InvoiceDetail> invoicedetail, int RequestId)
{
var OBJresult = new OutputResultStruct<KeyValuePair<string, int>>();
try
{
using (DataClassesDataContext Context = new DataClassesDataContext())
{
Invoice obj = new Invoice();
obj.UserId = invoice.UserId;
obj.RequestId = RequestId;
Context.Invoices.InsertOnSubmit(obj);
Context.SubmitChanges();
var Resultinvoicedetail = AddToInvoiceDetail(invoicedetail, obj.InvoiceId);
if (Resultinvoicedetail.IsValidResult==false)
{
Invoice ObjInvoiceDelete = Context.Invoices.Single(q => q.InvoiceId == obj.InvoiceId);
Context.Invoices.DeleteOnSubmit(ObjInvoiceDelete);
Context.SubmitChanges();
OBJresult.ErrorCode = Resultinvoicedetail.ErrorCode;
OBJresult.Description = Resultinvoicedetail.Description;
OBJresult.IsValidResult = false;
OBJresult.resultvalue = new List<KeyValuePair<string, int>>() ;
}
else
{
OBJresult.ErrorCode = Resultinvoicedetail.ErrorCode;
OBJresult.Description = Resultinvoicedetail.Description;
OBJresult.IsValidResult = true;
OBJresult.resultvalue = new List<KeyValuePair<string, int>>() { new KeyValuePair<string, int>("InsertId", obj.InvoiceId) };
}
}
}
catch (Exception ex)
{
OBJresult.ErrorCode = 2;
OBJresult.Description = ex.Message;
OBJresult.IsValidResult = false;
OBJresult.resultvalue = new List<KeyValuePair<string, int>>();
}
return OBJresult;
}
نحوه کار با فایل XML در #C
فایل XML
<?xml version="1.0" encoding="utf-8" ?>
<items>
<item>
<Key>123</Key>
</item>
<item>
<Key>451</Key>
</item>
</items>
حال در سی شارپ اینطوری صداش می زنیم و از آن استفاده می کنیم.
XmlNode xmlNode;
XmlDocument xmlDoc = new XmlDocument();
String htmlCode = string.Empty;
WebClient htmlDoc = new WebClient();
string AddresXml = HttpContext.Current.Server.MapPath(@"\App_Data\APIKeys.xml");
htmlCode = htmlDoc.DownloadString(AddresXml);
//htmlCode = htmlCode.Substring(htmlCode.IndexOf("<table class=\"comodities\" style=\"margin-top:4px;\">"), htmlCode.IndexOf("</table></center><br>") - htmlCode.IndexOf("<table class=\"comodities\" style=\"margin-top:4px;\">") + 8);
htmlCode = htmlCode.Replace("'", "\"");
htmlCode = htmlCode.Replace("</a>", "");
xmlDoc.LoadXml(htmlCode);
for (int i = 0; i < xmlDoc.ChildNodes.Count; i++)
{
if (xmlDoc.ChildNodes[i].Name == "items")
{
for (int j = 0; j < xmlDoc.ChildNodes[i].ChildNodes.Count; j++)
{
if (xmlDoc.ChildNodes[i].ChildNodes[j].Name == "item")
{
key = Convert.ToString(xmlDoc.ChildNodes[i].ChildNodes[j].ChildNodes[0].InnerText);
Guid.TryParse(key, out apiKey);
OBJGuid.Add(apiKey);
}
}
}
}
نحوه ایجاد Inner join با استفاده از دستورات لینکیو در سی شارپ
from t1 in db.Table1
join t2 in db.Table2 on t1.field equals t2.field
select new { t1.field2, t2.field3}