C# SqlCommand Example



private string connectionString = WebConfigurationManager.AppSettings["connectionString"];

public rmtoken ReadTokenFromDB(string eftkodu, string scope, int wsauthority)
{
    try
    {
        rmtoken rmtoken = new rmtoken();
        using (SqlConnection con = new SqlConnection(connectionString))
        {
            con.Open();
            SqlCommand cmd = new SqlCommand("select access_token, expires_in, refresh_token, tokendate from rmtoken where eftkodu='" + eftkodu
                + "' and scope='" + scope + "' and wsauthority=" + wsauthority.ToString(), con);
            SqlDataReader dataReader = cmd.ExecuteReader();
            if (dataReader.Read())
            {
                rmtoken.access_token = dataReader["access_token"].ToString();
                rmtoken.expires_in = Convert.ToInt32(dataReader["expires_in"]);
                rmtoken.refresh_token = dataReader["refresh_token"].ToString();
                rmtoken.tokendate = Convert.ToDateTime(dataReader["tokendate"]);
            }
            cmd.Dispose();
            con.Close();
        }
        return rmtoken;
    }
    catch
    {
        //log
        return null;
    }
}



Advertisements

C# POST Method using WebRequest

I will show you how to make a POST request using WebRequest and to create a token.


        public TokenOlusturmaCikti TokenOlusturma(TokenOlusturmaGirdi girdi)
        {
            TokenOlusturmaCikti cikti = null;
            WebRequest req = WebRequest.Create(TokenServisi);
            req.ContentType = "application/x-www-form-urlencoded";
            req.Method = "POST";

            string parameters = "";
            parameters += "state=" + girdi.state;
            parameters += "&grant_type=" + girdi.grant_type;
            parameters += "&scope=" + girdi.scope;
            parameters += "&username=" + girdi.username;
            parameters += "&password=" + girdi.password;
            parameters += "&client_id=" + girdi.client_id;
            parameters += "&client_secret=" + girdi.client_secret;
            byte[] bytes = Encoding.UTF8.GetBytes(parameters);

            req.ContentLength = bytes.Length;

            Stream stream = req.GetRequestStream();
            stream.Write(bytes, 0, bytes.Length);
            stream.Close();

            WebResponse res = req.GetResponse();
            if (res == null) return null;

            StreamReader sr = new StreamReader(res.GetResponseStream());
            string json = sr.ReadToEnd();

            cikti = JsonConvert.DeserializeObject(json);
            return cikti;
        }

1

Angular Example

Create a new folder

> mkdir angular6

> cd angular6

1

> ng new myproject

2

> cd myproject

Open the project in your editor. I am using VSCode.

> code .

Start the development server.

> ng serve –open

Create a new component.

> ng g c home

Create an another component.

> ng g c employees

3

app.module.ts


import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { EmployeesComponent } from './employees/employees.component';

import {RouterModule, Routes} from '@angular/router';
const routes: Routes = [
  { path: 'employees', component: EmployeesComponent },
  { path: 'home', component: HomeComponent }
];

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    EmployeesComponent
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(routes),
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.html


<!--The content below is only a placeholder and can be replaced.-->
<div style="text-align:center;">
  <h1>
    Welcome to {{ title }}!
  </h1>
  <img width="300" alt="Angular Logo" src="image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNTAgMjUwIj4KICAgIDxwYXRoIGZpbGw9IiNERDAwMzEiIGQ9Ik0xMjUgMzBMMzEuOSA2My4ybDE0LjIgMTIzLjFMMTI1IDIzMGw3OC45LTQzLjcgMTQuMi0xMjMuMXoiIC8+CiAgICA8cGF0aCBmaWxsPSIjQzMwMDJGIiBkPSJNMTI1IDMwdjIyLjItLjFWMjMwbDc4LjktNDMuNyAxNC4yLTEyMy4xTDEyNSAzMHoiIC8+CiAgICA8cGF0aCAgZmlsbD0iI0ZGRkZGRiIgZD0iTTEyNSA1Mi4xTDY2LjggMTgyLjZoMjEuN2wxMS43LTI5LjJoNDkuNGwxMS43IDI5LjJIMTgzTDEyNSA1Mi4xem0xNyA4My4zaC0zNGwxNy00MC45IDE3IDQwLjl6IiAvPgogIDwvc3ZnPg==">
</ div>
<h2>Here are some links to help you start: </h2>
<ul>
  
  <li>
    <h2><a>Home</a></h2>
  </li>
  <li>
    <h2><a>Employees</a></h2>
  </li>
</ul>



4

PowerBuilder – compute MD5 value for a file

OLEObject obj_md5, obj_stream, obj_dom, obj_element
integer li_rc, li_temp

If IsNull( as_filepath ) Then
	as_hata = "Dosya Yolu null değer dönmüştür!"
	Return -1
End If

li_temp = 1 //Initial Value

obj_md5 = CREATE OLEObject
li_rc = obj_md5.ConnectToNewObject("System.Security.Cryptography.MD5CryptoServiceProvider")
If li_rc = 0 Then//Success
	obj_stream = CREATE OLEObject
	li_rc = obj_stream.ConnectToNewObject("ADODB.Stream")	
	Choose Case li_rc		
		Case 0
			obj_stream.Open
			obj_stream.Type = 1
			obj_stream.LoadFromFile(as_filepath)
			
			obj_md5.ComputeHash_2(obj_stream.Read)
			
			obj_dom = CREATE OLEObject
			li_rc = obj_dom.ConnectToNewObject("Msxml2.DOMDocument.6.0")	
			If li_rc = 0 Then
				obj_element = obj_dom.CreateElement("tmp")//Gecici Element Olusturma	
				obj_element.DataType = "bin.hex"//Cevirme	 
				obj_element.NodeTypedValue = obj_md5.Hash
				
				as_md5 = obj_element.Text//Cevirilmis MD5 Degeri Alma		
			Else
				li_temp = -1
				as_hata = "Msxml2.DOMDocument.6.0 hata almıştır! li_rc : " + string(li_rc)				
			End If
			
			obj_stream.Close
		Case Else
			li_temp = -1
			as_hata = "ADODB.Stream hata almıştır! li_rc : " + string(li_rc)		
	End Choose	
Else	
	li_temp = -1
	as_hata = "MD5CryptoServiceProvider hata almıştır! li_rc : " + string(li_rc)	
End If

DESTROY obj_dom
DESTROY obj_stream
DESTROY obj_md5
Return li_temp

PowerBuilder Excel

oleobject lole_excel
integer li_rc
string ls_filepath
boolean lb_rc, lb_flag

sle_excelpath.text = Trim(sle_excelpath.text)

ls_filepath = "C:\Temp\test.xlsx"
lb_rc = FileExists(ls_filepath)
if lb_rc then
	lb_rc = FileDelete(ls_filepath)
	choose case lb_rc
		case false
			MessageBox("Error",   "Close " + ls_filepath + " file", Information!)
			return
	end choose
end if

lole_excel = create oleobject

li_rc = lole_excel.ConnectToNewObject( "excel.application")
if li_rc < 0 then
                destroy lole_excel
                MessageBox("Connecting to New Object Failed",   "Error: " + String(li_rc))
                return -1
end if

lole_excel.WorkBooks.Open(sle_excelpath.text)

lole_excel.Application.WorkBooks(1).Worksheets("Sheet1").Rows(1).Insert();

// Set the cell value
lole_excel.Application.WorkBooks(1).Worksheets("Sheet1").Cells(2, 3).value = "New value"

// Save
lole_excel.Application.WorkBooks(1).Save()
// Quit
lole_excel.Application.Quit()
lole_excel.DisconnectObject()

destroy lole_excel
return

How to send a PDF file using MultipartFormDataContent in C#

How to send a PDF file using MultipartFormDataContent in C#

I will explain to consume a Web API that requires multipart/form-data. Also I will show you how to send an PDF file from ASP.NET MVC Web App to the Web API.

I used the following code to send the PDF file and JSON values.


	[HttpPost]
        public async Task Index(Person person, HttpPostedFileBase file)
        {
	    byte[] data;
			
            var content = new MultipartFormDataContent();

            var fileName = Path.GetFileName(file.FileName);
			
            MemoryStream memoryStream = new MemoryStream();
            file.InputStream.CopyTo(memoryStream);
            data = memoryStream.ToArray();
			
            ByteArrayContent bytecontent = new ByteArrayContent(data);
            bytecontent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data");
            bytecontent.Headers.ContentDisposition.Name = "\"CV\"";
            bytecontent.Headers.ContentDisposition.FileName = fileName;
            bytecontent.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
            content.Add(bytecontent);
			
            memoryStream.Dispose();

            string json = "{\"name\":\"" + person.name + "\", " +
                "\"surname\":\"" + person.surname + "\", " +
                "\"age\":\"" + person.age + "\"}";
            content.Add(new StringContent(json), "jsonParameters");

            var client = new HttpClient();
            //client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(token_type, access_token);

            string output = "";
            using (var message = await client.PostAsync(url, content))
            {
                output = await message.Content.ReadAsStringAsync();
            }

            return View(person);
        }

ASP.NET Web API Post

The Action name must start with the “POST” word for HTML POST method in ASP.NET Web API.

You can name the action name as follows.

Post()
PostNewPerson()
PostData()

In the “POST” action method, you need to validate the model using ModelState.IsValid.

	public BankNotifyOut Post(BankNotifyIn Input)
        {
            BankNotifyOut output = new BankNotifyOut();
            if (!ModelState.IsValid)
            {  
                ...
				return output;
            }
			...
            return output;

        }

There is a way to make Web API treat your response as JSON :

– Open the “App_Start/WebApiConfig.cs” file and then Add the following code into the “Register” method.

config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

For example;

You can try the example using Postman.

– Add the key-value pair “Content-Type : application/json” in the section “Headers” .

– Then click on the “Send” button.

As you can see above, the JSON request automatically assigned to the parameter “BankaBildirimGirdi girdi” through Model binding and so we got an output value as JSON data as shown below.